
    ^j                    z    d dl mZ d dlmZ d dlmZmZ d dlZd dl	mZ
 erd dlZd	dZd
dZe G d d             Zy)    )annotations)	dataclass)TYPE_CHECKINGAnyNc                v    t        | t        j                        xr | j                  |fk(  }|st	        d      y)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)class_idnis_valids      j/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/classification/core.py_validate_class_idsr      s8     (BJJ/JHNNqd4JHJKK     c                |    | :t        | t        j                        xr | j                  |fk(  }|st	        d      yy)zE
    Ensure that confidence is a 1d np.ndarray with (n, ) shape.
    Nz1confidence must be 1d np.ndarray with (n, ) shaper   )
confidencer   r   s      r   _validate_confidencer      sE     j"**5R*:J:Jqd:RPQQ  r   c                  |    e Zd ZU ded<   dZded<   ddZddZedd       Zedd	       Z	edd
       Z
	 	 	 	 ddZy)Classificationsznpt.NDArray[np.int_]r   Nznpt.NDArray[np.floating] | Noner   c                    t        | j                        }t        | j                  |       t        | j                  |       y)z5
        Validate the classification inputs.
        N)lenr   r   r   r   )selfr   s     r   __post_init__zClassifications.__post_init__%   s.     DMM1-T__a0r   c                ,    t        | j                        S )z8
        Returns the number of classifications.
        )r   r   )r   s    r   __len__zClassifications.__len__.   s     4==!!r   c                   |j                  d      j                         j                         j                         d   }t	        |      dk(  rP | t        j                  g t
        j                        t        j                  g t
        j                              S t        j                  t	        |            } | ||      S )a  
        Creates a Classifications instance from a
        [clip](https://github.com/openai/clip) inference result.

        Args:
            clip_results: The inference result from clip model.

        Returns:
            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   dtyper   r   )
softmaxcpudetachnumpyr   r
   arrayint_float32arange)clsclip_resultsr   	class_idss       r   	from_clipzClassifications.from_clip4   s    : "))b)1557>>@FFHK
z?a"BGG488Bbjj9 
 IIc*o.	I*==r   c                    |j                   j                  j                         j                         } | t	        j
                  |j                  d         |      S )a  
        Creates a Classifications instance from a
        [ultralytics](https://github.com/ultralytics/ultralytics) inference result.

        Args:
            ultralytics_results: The inference result from ultralytics model.

        Returns:
            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   s      r   from_ultralyticsz Classifications.from_ultralytics\   sH    2 )..33779??A
BIIj&6&6q&9:zRRr   c                l   |j                         j                         j                         d   }t        |      dk(  rP | t	        j
                  g t        j                        t	        j
                  g t        j                              S t	        j                  t        |            } | ||      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:
            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*   r+   r,   )r-   timm_resultsr   r   s       r   	from_timmzClassifications.from_timmx   s    F "%%'..0668;
z?a"BGG488Bbjj9 
 99S_-H<<r   c                    | j                   t        d      t        j                  | j                         ddd   }|d| }| j                  |   }| j                   |   }||fS )a  
        Retrieve the top k class IDs and confidences,
            ordered in descending order by confidence.

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

        Returns:
            A tuple containing the top k class IDs and confidences.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> classifications = sv.Classifications(
            ...     class_id=np.array([0, 1, 2]),
            ...     confidence=np.array([0.3, 0.9, 0.5])
            ... )
            >>> classifications.get_top_k(1)
            (array([1]), array([0.9]))

            ```
        Nz1top_k could not be calculated, confidence is Noner    )r   r   r
   argsortr   )r   kordertop_k_ordertop_k_class_idtop_k_confidences         r   	get_top_kzClassifications.get_top_k   si    4 ??"PQQ

4??+DbD1BQi{3??;7///r   )returnNone)rA   int)r.   ztorch.TensorrA   r   )r4   r   rA   r   )r7   r   rA   r   )r;   rC   rA   z5tuple[npt.NDArray[np.int_], npt.NDArray[np.floating]])__name__
__module____qualname____annotations__r   r   r   classmethodr0   r5   r8   r@    r   r   r   r       sr    ""26J/61" %> %>N S S6 += +=Z"0"0	>"0r   r   )r   r   r   rC   rA   rB   )r   r   r   rC   rA   rB   )
__future__r   dataclassesr   typingr   r   r(   r
   numpy.typingnpttorchr   r   r   rI   r   r   <module>rP      sB    " ! %  LR g0 g0 g0r   