o
    Ďi                     @  sr   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mZmZ G d	d
 d
ZdS )    )annotations)AnyN)Category)logger)ObjectPrediction)check_requirements)empty_cuda_cacheselect_devicec                   @  s   e Zd ZU dZded< 										d>d?ddZd@dAddZdd ZdBd!d"Zd@dCd#d$Z	d%d& Z
dDd)d*Zd+d+ggdfdEd/d0Zd1d2 Zd+d+ggdfdFd5d6ZedGd8d9ZedGd:d;Zed<d= ZdS )HDetectionModelNlist[str] | Nonerequired_packages      ?333333?T
model_path
str | Nonemodel
Any | Noneconfig_pathdevicemask_thresholdfloatconfidence_thresholdcategory_mappingdict | Nonecategory_remappingload_at_initbool
image_size
int | Nonec                 C  st   || _ || _d| _|| _|| _|| _|| _|
| _d| _d| _	| 
| |   |	r8|r2| | dS |   dS dS )a  Init object detection/instance segmentation model.

        Args:
            model_path: str
                Path for the instance segmentation model weight
            config_path: str
                Path for the mmdetection instance segmentation model config file
            device: Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc.
            mask_threshold: float
                Value to threshold mask pixels, should be between 0 and 1
            confidence_threshold: float
                All predictions with score < confidence_threshold will be discarded
            category_mapping: dict: str to str
                Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"}
            category_remapping: dict: str to int
                Remap category ids based on category names, after performing inference e.g. {"car": 3}
            load_at_init: bool
                If True, automatically loads the model at initialization
            image_size: int
                Inference input size.
        N)r   r   r   r   r   r   r   r   _original_predictions!_object_prediction_list_per_image
set_devicecheck_dependencies	set_model
load_model)selfr   r   r   r   r   r   r   r   r   r    r&   L/home/jeff/fluffinator/venv/lib/python3.10/site-packages/sahi/models/base.py__init__   s"   #
zDetectionModel.__init__packagesreturnNonec                 C  s,   |dur|nt | dg }|rt| dS dS )zEnsures required dependencies are installed.

        If 'packages' is None, uses self.required_packages. Subclasses may still call with a custom list for dynamic
        needs.
        Nr   )getattrr   )r%   r)   pkgsr&   r&   r'   r"   J   s   z!DetectionModel.check_dependenciesc                 C     t  )zThis function should be implemented in a way that detection model should be initialized and set to
        self.model.

        (self.model_path, self.config_path, and self.device should be utilized)
        NotImplementedErrorr%   r&   r&   r'   r$   T   s   zDetectionModel.load_modelr   c                 K  r.   )z
        This function should be implemented to instantiate a DetectionModel out of an already loaded model
        Args:
            model: Any
                Loaded model
        r/   )r%   r   kwargsr&   r&   r'   r#   \   s   zDetectionModel.set_modelc                 C  s   t || _dS )zSets the device pytorch should use for the model.

        Args:
            device: Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc.
        N)r	   r   )r%   r   r&   r&   r'   r!   e   s   zDetectionModel.set_devicec                 C  s   d| _ t  dS )zUnloads the model from CPU/GPU.N)r   r   r1   r&   r&   r'   unload_modeln   s   
zDetectionModel.unload_modelimage
np.ndarrayc                 C  r.   )a-  This function should be implemented in a way that prediction should be performed using self.model and the
        prediction result should be set to self._original_predictions.

        Args:
            image: np.ndarray
                A numpy array that contains the image to be predicted.
        r/   )r%   r4   r&   r&   r'   perform_inferences   s   z DetectionModel.perform_inferencer   shift_amount_listlist[list[int]] | Nonefull_shape_listc                 C  r.   )a  This function should be implemented in a way that self._original_predictions should be converted to a list of
        prediction.ObjectPrediction and set to self._object_prediction_list.

        self.mask_threshold can also be utilized.
        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%   r7   r9   r&   r&   r'   8_create_object_prediction_list_from_original_predictions}   s   zGDetectionModel._create_object_prediction_list_from_original_predictionsc                 C  sz   | j du r	tdt| jtstdt| j  dS | jD ]}|D ]}t|j	j
}| j | }t||j	jd|_	q#qdS )zMApplies category remapping based on mapping given in self.category_remapping.Nz&self.category_remapping cannot be Nonez9Unknown type for self._object_prediction_list_per_image: )idname)r   
ValueError
isinstancer    listr   errortypestrcategoryr;   r   r<   )r%   object_prediction_listobject_predictionold_category_id_strnew_category_id_intr&   r&   r'   _apply_category_remapping   s    


z(DetectionModel._apply_category_remappingshift_amount
full_shapec                 C  s$   | j ||d | jr|   dS dS )a  Converts original predictions of the detection model to a list of prediction.ObjectPrediction object.

        Should be called after perform_inference().
        Args:
            shift_amount: list
                To shift the box and mask predictions from sliced image to full sized image,
                    should be in the form of [shift_x, shift_y]
            full_shape: list
                Size of the full image after shifting, should be in the form of [height, width]
        )r7   r9   N)r:   r   rH   )r%   rI   rJ   r&   r&   r'   convert_original_predictions   s   z+DetectionModel.convert_original_predictionslist[list[ObjectPrediction]]c                 C  s*   | j d u rg S t| j dkrg S | j d S )Nr   )r    lenr1   r&   r&   r'   rD      s
   

z%DetectionModel.object_prediction_listc                 C  s
   | j pg S N)r    r1   r&   r&   r'    object_prediction_list_per_image   s   
z/DetectionModel.object_prediction_list_per_imagec                 C  s   | j S rN   )r   r1   r&   r&   r'   original_predictions   s   z#DetectionModel.original_predictions)
NNNNr   r   NNTN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rN   )r)   r   r*   r+   )r   r   )r   r   )r4   r5   )r7   r8   r9   r8   )rI   r8   rJ   r8   )r*   rL   )__name__
__module____qualname__r   __annotations__r(   r"   r$   r#   r!   r3   r6   r:   rH   rK   propertyrD   rO   rP   r&   r&   r&   r'   r
      s@   
 9

		
r
   )
__future__r   typingr   numpynpsahi.annotationr   sahi.loggerr   sahi.predictionr   sahi.utils.import_utilsr   sahi.utils.torch_utilsr   r	   r
   r&   r&   r&   r'   <module>   s    