o
    e                     @  s^   d dl mZ d dlmZ d dlmZmZmZ d dlZ	dddZ
dddZeG dd dZdS )    )annotations)	dataclass)AnyOptionalTupleNclass_idr   nintreturnNonec                 C  s(   t | tjo| j|fk}|stddS )zC
    Ensure that class_id is a 1d np.ndarray with (n, ) shape.
    z/class_id must be 1d np.ndarray with (n, ) shapeN
isinstancenpndarrayshape
ValueError)r   r   is_valid r   N/var/www/myenv/lib/python3.10/site-packages/supervision/classification/core.py_validate_class_ids	   s   r   
confidencec                 C  s4   | durt | tjo| j|fk}|stddS dS )zE
    Ensure that confidence is a 1d np.ndarray with (n, ) shape.
    Nz1confidence must be 1d np.ndarray with (n, ) shaper   )r   r   r   r   r   r   _validate_confidence   s   r   c                   @  sj   e Zd ZU ded< dZded< ddd	ZdddZedddZedddZ	edddZ
dddZdS )Classificationsz
np.ndarrayr   NzOptional[np.ndarray]r   r
   r   c                 C  s&   t | j}t| j| t| j| dS )z5
        Validate the classification inputs.
        N)lenr   r   r   r   )selfr   r   r   r   __post_init__!   s   
zClassifications.__post_init__r	   c                 C  s
   t | jS )z8
        Returns the number of classifications.
        )r   r   )r   r   r   r   __len__*   s   
zClassifications.__len__c                 C  sZ   |j dd   d }t|dkr | tg tg dS tt|}| ||dS )a.  
        Creates a Classifications instance from a
        [clip](https://github.com/openai/clip) inference result.

        Args:
            clip_results (np.ndarray): The inference result from clip model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            >>> from PIL import Image
            >>> import clip
            >>> import supervision as sv

            >>> model, preprocess = clip.load('ViT-B/32')

            >>> image = cv2.imread(SOURCE_IMAGE_PATH)
            >>> image = preprocess(image).unsqueeze(0)

            >>> text = clip.tokenize(["a diagram", "a dog", "a cat"])
            >>> output, _ = model(image, text)
            >>> classifications = sv.Classifications.from_clip(output)
            ```
        )dimr   r   r   )softmaxcpudetachnumpyr   r   arrayarange)clsclip_resultsr   	class_idsr   r   r   	from_clip0   s
   zClassifications.from_clipc                 C  s(   |j j  }| t|jd |dS )a  
        Creates a Classifications instance from a
        [ultralytics](https://github.com/ultralytics/ultralytics) inference result.

        Args:
            ultralytics_results (ultralytics.engine.results.Results):
                The inference result from ultralytics model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            >>> import cv2
            >>> from ultralytics import YOLO
            >>> import supervision as sv

            >>> image = cv2.imread(SOURCE_IMAGE_PATH)
            >>> model = YOLO('yolov8n-cls.pt')

            >>> output = model(image)[0]
            >>> classifications = sv.Classifications.from_ultralytics(output)
            ```
        r   r   )probsdatar!   r#   r   r%   r   )r&   ultralytics_resultsr   r   r   r   from_ultralyticsU   s   z Classifications.from_ultralyticsc                 C  sR   |    d }t|dkr| tg tg dS tt|}| ||dS )a  
        Creates a Classifications instance from a
        [timm](https://huggingface.co/docs/hub/timm) inference result.

        Args:
            timm_results: The inference result from timm model.

        Returns:
            Classifications: A new Classifications object.

        Example:
            ```python
            >>> from PIL import Image
            >>> import timm
            >>> from timm.data import resolve_data_config, create_transform
            >>> import supervision as sv

            >>> model = timm.create_model(
            ...     model_name='hf-hub:nateraw/resnet50-oxford-iiit-pet',
            ...     pretrained=True
            ... ).eval()

            >>> config = resolve_data_config({}, model=model)
            >>> transform = create_transform(**config)

            >>> image = Image.open(SOURCE_IMAGE_PATH).convert('RGB')
            >>> x = transform(image).unsqueeze(0)

            >>> output = model(x)

            >>> classifications = sv.Classifications.from_timm(output)
            ```
        r   r   )r!   r"   r#   r   r   r$   r%   )r&   timm_resultsr   r   r   r   r   	from_timmr   s
   #zClassifications.from_timmkTuple[np.ndarray, np.ndarray]c                 C  sP   | j du r	tdt| j ddd }|d| }| j| }| j | }||fS )aJ  
        Retrieve the top k class IDs and confidences,
            ordered in descending order by confidence.

        Args:
            k (int): The number of top class IDs and confidences to retrieve.

        Returns:
            Tuple[np.ndarray, np.ndarray]: A tuple containing
                the top k class IDs and confidences.

        Example:
            ```python
            >>> import supervision as sv

            >>> classifications = sv.Classifications(...)

            >>> classifications.get_top_k(1)

            (array([1]), array([0.9]))
            ```
        Nz1top_k could not be calculated, confidence is Noner   )r   r   r   argsortr   )r   r0   ordertop_k_ordertop_k_class_idtop_k_confidencer   r   r   	get_top_k   s   


zClassifications.get_top_k)r
   r   )r
   r	   )r
   r   )r0   r	   r
   r1   )__name__
__module____qualname____annotations__r   r   r   classmethodr)   r-   r/   r7   r   r   r   r   r      s   
 

	$*r   )r   r   r   r	   r
   r   )r   r   r   r	   r
   r   )
__future__r   dataclassesr   typingr   r   r   r#   r   r   r   r   r   r   r   r   <module>   s    

	
