Ë
    ¼Ó^jL¾  ã                  óV  — d dl mZ d dlZd dlmZmZ d dlmZmZ d dl	m
Z
mZ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 d dlmZ  ej>                  e «      Z!ee"e#e$e"   e$e%   ejL                  ejN                     ejL                  ejP                     f   Z)e*e)e)f   Z+ee"ejX                  e
   ejL                  ejZ                     e$e
   e#f   Z.eejL                  ejZ                     e$e
   e#f   Z/	 	 	 	 	 	 dd„Z0	 	 	 	 dd„Z1 ed¬«       G d„ d«      «       Z2y)é    )ÚannotationsN)ÚIterableÚIterator)Ú	dataclassÚfield)ÚAnyÚUnionÚcast)ÚCLASS_NAME_DATA_FIELD)Ú
Detections)Úget_data_itemÚis_data_equal)ÚOverlapMetricÚbox_non_max_suppression)Úwarn_deprecated)Ú_validate_keypoints_fieldsc                óJ   — | �|€
| d u xr |d u S t        j                  | |«      S ©N)ÚnpÚarray_equal)ÚfirstÚseconds     úf/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/key_points/core.pyÚ_optional_array_equalr   *   s1   € ð €}˜˜Ø˜ˆ}Ò/ ¨4 Ð/Ü�>‰>˜% Ó(Ð(ó    c                ó   — t        | t        t        j                  f«      r-t	        t
        t        j                  t        | «      g«      «      S t        | t        j                  «      rD| j                  t        k(  r1t	        t
        t        j                  | j                  «       «      «      S t        | t        j                  «      r.| j                  dk(  rt	        t
        | j                  d«      «      S t        | t        «      rJ| rHt        d„ | D «       «      r6t	        t
        t        j                  t        j                  | «      «      «      S | S )a�  Normalise *i* to a 1-D row index for 1-D per-object fields.

    Handles:
    - Python int or np.integer scalar  -> np.array([int(i)])
    - boolean np.ndarray (any shape)   -> np.flatnonzero(i.ravel())
    - non-bool 0-d np.ndarray          -> reshaped to shape (1,)
    - list of bool                     -> np.flatnonzero(np.array(i))
    - slice, list of ints, 1-D ndarray -> returned as-is
    r   é   c              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­wr   ©Ú
isinstanceÚbool©Ú.0Úxs     r   ú	<genexpr>z'_normalize_row_index.<locals>.<genexpr>E   s   è ø€ Ò(HÀ¬°A´t×)<Ñ(Hùó   ‚)r    Úintr   Úintegerr
   Ú_NormalizedRowIndexÚarrayÚndarrayÚdtyper!   ÚflatnonzeroÚravelÚndimÚreshapeÚlistÚall)Úis    r   Ú_normalize_row_indexr4   3   sÔ   € ô �!”cœ2Ÿ:™:Ð&Ô'ÜÔ'¬¯©´3°q³6°(Ó);Ó<Ð<Ü�!”R—Z‘ZÔ  Q§W¡W´¢_ÜÔ'¬¯©¸¿¹»	Ó)BÓCÐCÜ�!”R—Z‘ZÔ  Q§V¡V¨q¢[ÜÔ'¨¯©°1«Ó6Ð6Ü�!”TÔ™q¤SÑ(HÀaÔ(HÔ%HÜÔ'¬¯©¼¿¹À»Ó)DÓEÐEØ€Hr   F)Úinitc                  óú  — e Zd ZU dZded<   dZded<   dZded<   dZded	<   dZd
ed<    e	e
¬«      Zded<   	 	 	 	 	 d&ddœ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d'd„Zd(d„Zed)d„«       Zej                   d*d„«       Zd+d„Z	 	 d,d„Zd-d„Zed.d„«       Ze	 	 	 	 	 	 d/d„«       Zed0d„«       Zed1d„«       Zed2d„«       Zed3d„«       Zd4d„Z	 	 	 	 d5d„Zd6d„Zed7d „«       Zd8d!„Zd"d#e jB                  f	 	 	 	 	 	 	 d9d$„Z"	 d:	 	 	 d;d%„Z#y)<Ú	KeyPointsu#  
    The `sv.KeyPoints` class in the Supervision library standardizes results from
    various keypoint detection and pose estimation models into a consistent format. This
    class simplifies data manipulation and filtering, providing a uniform API for
    integration with Supervision [keypoints annotators](/latest/keypoint/annotators).

    === "RF-DETR"

        [RF-DETR](https://github.com/roboflow/rf-detr) keypoint models return
        `sv.KeyPoints` directly from `model.predict()` â€” no additional
        conversion is needed.

        ```python
        import cv2
        import supervision as sv
        from rfdetr import RFDETRKeypointPreview

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        model = RFDETRKeypointPreview()

        key_points = model.predict(image)
        ```

    === "Ultralytics"

        Use [`sv.KeyPoints.from_ultralytics`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_ultralytics)
        method, which accepts [YOLOv8-pose](https://docs.ultralytics.com/models/yolov8/), [YOLO11-pose](https://docs.ultralytics.com/models/yolo11/)
        [pose](https://docs.ultralytics.com/tasks/pose/) result.

        ```python
        import cv2
        import supervision as sv
        from ultralytics import YOLO

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        model = YOLO('yolo11s-pose.pt')

        result = model(image)[0]
        key_points = sv.KeyPoints.from_ultralytics(result)
        ```

    === "Inference"

        Use [`sv.KeyPoints.from_inference`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_inference)
        method, which accepts [Inference](https://inference.roboflow.com/) pose result.

        ```python
        import cv2
        import supervision as sv
        from inference import get_model

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        model = get_model(model_id="<POSE_MODEL_ID>", api_key="<ROBOFLOW_API_KEY>")

        result = model.infer(image)[0]
        key_points = sv.KeyPoints.from_inference(result)
        ```

    === "MediaPipe"

        Use [`sv.KeyPoints.from_mediapipe`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_mediapipe)
        method, which accepts [MediaPipe](https://github.com/google-ai-edge/mediapipe)
        pose result.


        ```python
        import cv2
        import mediapipe as mp
        import supervision as sv

        image = cv2.imread("<SOURCE_IMAGE_PATH>")
        image_height, image_width, _ = image.shape
        mediapipe_image = mp.Image(
            image_format=mp.ImageFormat.SRGB,
            data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

        options = mp.tasks.vision.PoseLandmarkerOptions(
            base_options=mp.tasks.BaseOptions(
                model_asset_path="pose_landmarker_heavy.task"
            ),
            running_mode=mp.tasks.vision.RunningMode.IMAGE,
            num_poses=2)

        PoseLandmarker = mp.tasks.vision.PoseLandmarker
        with PoseLandmarker.create_from_options(options) as landmarker:
            pose_landmarker_result = landmarker.detect(mediapipe_image)

        key_points = sv.KeyPoints.from_mediapipe(
            pose_landmarker_result, (image_width, image_height))
        ```

    === "Transformers"

        Use [`sv.KeyPoints.from_transformers`](/latest/keypoint/core/#supervision.key_points.core.KeyPoints.from_transformers)
        method, which accepts [ViTPose](https://huggingface.co/docs/transformers/en/model_doc/vitpose) result.

        ```python
        from PIL import Image
        import requests
        import supervision as sv
        import torch
        from transformers import (
            AutoProcessor,
            RTDetrForObjectDetection,
            VitPoseForPoseEstimation,
        )

        device = "cuda" if torch.cuda.is_available() else "cpu"
        image = Image.open("<SOURCE_IMAGE_PATH>")

        DETECTION_MODEL_ID = "PekingU/rtdetr_r50vd_coco_o365"

        detection_processor = AutoProcessor.from_pretrained(DETECTION_MODEL_ID, use_fast=True)
        detection_model = RTDetrForObjectDetection.from_pretrained(DETECTION_MODEL_ID, device_map=DEVICE)

        inputs = detection_processor(images=frame, return_tensors="pt").to(DEVICE)

        with torch.no_grad():
            outputs = detection_model(**inputs)

        target_size = torch.tensor([(frame.height, frame.width)])
        results = detection_processor.post_process_object_detection(
            outputs, target_sizes=target_size, threshold=0.3)

        detections = sv.Detections.from_transformers(results[0])
        boxes = sv.xyxy_to_xywh(detections[detections.class_id == 0].xyxy)

        POSE_ESTIMATION_MODEL_ID = "usyd-community/vitpose-base-simple"

        pose_estimation_processor = AutoProcessor.from_pretrained(POSE_ESTIMATION_MODEL_ID)
        pose_estimation_model = VitPoseForPoseEstimation.from_pretrained(
            POSE_ESTIMATION_MODEL_ID, device_map=DEVICE)

        inputs = pose_estimation_processor(frame, boxes=[boxes], return_tensors="pt").to(DEVICE)

        with torch.no_grad():
            outputs = pose_estimation_model(**inputs)

        results = pose_estimation_processor.post_process_pose_estimation(outputs, boxes=[boxes])
        key_point = sv.KeyPoints.from_transformers(results[0])
        ```

    Attributes:
        xy: An array of shape `(n, m, 2)` containing
            `n` detected objects, each composed of `m` equally-sized
            sets of key points, where each point is `[x, y]`.
        class_id: An array of shape
            `(n,)` containing the class ids of the detected objects.
        keypoint_confidence: An array of shape
            `(n, m)` containing the confidence scores of each keypoint.
        detection_confidence: An array of shape
            `(n,)` containing the detection-level confidence scores.
        visible: An optional boolean array of shape
            `(n, m)` indicating which keypoints are visible. When ``None``,
            all keypoints are treated as visible. Set this to filter anchors
            without removing data: ``key_points.visible = key_points.keypoint_confidence > 0.3``.
        data: A dictionary containing additional
            data where each key is a string representing the data type, and the value
            is either a NumPy array or a list of corresponding data of length `n`
            (one entry per detected object).
    únpt.NDArray[np.float32]ÚxyNúnpt.NDArray[np.int_] | NoneÚclass_idúnpt.NDArray[np.float32] | NoneÚkeypoint_confidenceÚdetection_confidenceúnpt.NDArray[np.bool_] | NoneÚvisible)Údefault_factoryz.dict[str, npt.NDArray[np.generic] | list[Any]]Údata)Ú
confidencec               ó¸   — |�|�t        d«      ‚t        d«       |}|| _        || _        || _        || _        || _        |�|ni | _        | j                  «        y)a÷  Initialize KeyPoints.

        Args:
            xy: Array of shape `(n, m, 2)` with keypoint coordinates.
            class_id: Array of shape `(n,)` with class IDs. Defaults to None.
            keypoint_confidence: Array of shape `(n, m)` with per-keypoint
                confidence scores. Defaults to None.
            detection_confidence: Array of shape `(n,)` with detection-level
                confidence scores. Defaults to None.
            visible: Boolean array of shape `(n, m)` indicating visible
                keypoints. Defaults to None.
            data: Dictionary of additional per-detection data arrays.
                Defaults to an empty dict.
            confidence: Deprecated since `0.29.0`, removed in `0.32.0`.
                Use ``keypoint_confidence`` instead. Raises ``ValueError``
                if passed together with ``keypoint_confidence``.

        Raises:
            ValueError: If both ``confidence`` and ``keypoint_confidence``
                are provided.
        Nuw   Cannot pass both 'confidence' and 'keypoint_confidence'. 'confidence' is deprecated â€” use 'keypoint_confidence' only.zˆ'confidence' parameter in `KeyPoints()` is deprecated since `0.29.0` and will be removed in `0.32.0`. Use 'keypoint_confidence' instead.)	Ú
ValueErrorr   r9   r;   r=   r>   r@   rB   Ú__post_init__)Úselfr9   r;   r=   r>   r@   rB   rC   s           r   Ú__init__zKeyPoints.__init__õ   sz   € ð@ Ð!Ø"Ð.Ü ðUóð ô ð1ôð
 #-ÐàˆŒØ ˆŒØ#6ˆÔ Ø$8ˆÔ!ØˆŒØ Ð,‘D°"ˆŒ	Ø×ÑÕr   c                óž   — t        | j                  | j                  | j                  | j                  | j
                  | j                  ¬«       y )N)r9   r;   rC   r>   r@   rB   )r   r9   r;   r=   r>   r@   rB   ©rG   s    r   rF   zKeyPoints.__post_init__*  s8   € Ü"Ø�w‰wØ—]‘]Ø×/Ñ/Ø!%×!:Ñ!:Ø—L‘LØ—‘ö	
r   c                ó0   — t        d«       | j                  S )z=Deprecated since 0.29.0. Use ``keypoint_confidence`` instead.ú}'KeyPoints.confidence' is deprecated since 0.29.0 and will be removed in 0.32.0. Use 'KeyPoints.keypoint_confidence' instead.©r   r=   rJ   s    r   rC   zKeyPoints.confidence4  s    € ô 	ðNô	
ð ×'Ñ'Ð'r   c                ó(   — t        d«       || _        y )NrL   rM   )rG   Úvalues     r   rC   zKeyPoints.confidence=  s   € äðNô	
ð $)ˆÕ r   c                ó,   — t        | j                  «      S )a­  
        Returns the number of objects in the `sv.KeyPoints` object.

        Returns:
            The number of objects.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> xy = np.array([[[10, 20], [30, 40]]], dtype=np.float32)
            >>> key_points = sv.KeyPoints(xy=xy)
            >>> len(key_points)
            1

            ```
        )Úlenr9   rJ   s    r   Ú__len__zKeyPoints.__len__E  s   € ô$ �4—7‘7‹|Ðr   c              #  ó  K  — t        t        | j                  «      «      D ]a  }| j                  |   | j                  �| j                  |   nd| j                  �| j                  |   ndt        | j                  |«      f–— Œc y­w)z—
        Iterates over the Keypoint object and yield a tuple of
        `(xy, keypoint_confidence, class_id, data)` for each object detection.
        N)ÚrangerQ   r9   r=   r;   r   rB   )rG   r3   s     r   Ú__iter__zKeyPoints.__iter__Y  s}   è ø€ ô ”s˜4Ÿ7™7“|Ó$ò 	ˆAà—‘˜‘
à×+Ñ+Ð7ð ×(Ñ(¨Ò+àØ$(§M¡MÐ$=�—‘˜aÒ À4Ü˜dŸi™i¨Ó+ðó ñ	ùs   ‚BBc                óÌ  — t        |t        «      st        S t        t	        j
                  | j                  |j                  «      t        | j                  |j                  «      t        | j                  |j                  «      t        | j                  |j                  «      t        | j                  |j                  «      t        | j                  |j                  «      g«      S r   )r    r7   ÚNotImplementedr2   r   r   r9   r   r;   r=   r>   r@   r   rB   )rG   Úothers     r   Ú__eq__zKeyPoints.__eq__q  s¦   € Ü˜%¤Ô+Ü!Ð!Üä—‘˜tŸw™w¨¯©Ó1Ü% d§m¡m°U·^±^ÓDÜ%Ø×,Ñ,¨e×.GÑ.Góô &Ø×-Ñ-¨u×/IÑ/Ióô & d§l¡l°E·M±MÓBÜ˜dŸi™i¨¯©Ó4ðó
ð 	
r   c                ó,  — t        |t        «      rt        d«      ‚t        |d«      r|j	                  dd¬«      }nt        |d«      r|j                  «       }|j                  d«      s| j                  «       S g }g }g }g }|d   D ]‡  }g }g }|d   D ]/  }	|j                  |	d   |	d	   g«       |j                  |	d
   «       Œ1 |j                  |«       |j                  |«       |j                  |d   «       |j                  |d   «       Œ‰ t        t        j                  |«      i}
 | t        j                  |t        j                  ¬«      t        j                  |t        j                  ¬«      t        j                  |t        ¬«      |
¬«      S )a”  
        Create a `sv.KeyPoints` object from the [Roboflow](https://roboflow.com/)
        API inference result or the [Inference](https://inference.roboflow.com/)
        package results.

        Args:
            inference_result: The result from the
                Roboflow API or Inference package containing predictions with keypoints.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
                and class names, and confidences of each keypoint.

        Examples:
            ```python
            import cv2
            import supervision as sv
            from inference import get_model

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = get_model(model_id="<POSE_MODEL_ID>", api_key="<ROBOFLOW_API_KEY>")

            result = model.infer(image)[0]
            key_points = sv.KeyPoints.from_inference(result)
            ```

            ```python
            import cv2
            import supervision as sv
            from inference_sdk import InferenceHTTPClient

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            client = InferenceHTTPClient(
                api_url="https://detect.roboflow.com",
                api_key="<ROBOFLOW_API_KEY>"
            )

            result = client.infer(image, model_id="<POSE_MODEL_ID>")
            key_points = sv.KeyPoints.from_inference(result)
            ```
        z}from_inference() operates on a single result at a time.You can retrieve it like so:  inference_result = model.infer(image)[0]ÚdictT)Úexclude_noneÚby_aliasÚjsonÚpredictionsÚ	keypointsr$   ÚyrC   r;   Úclass©r,   ©r9   r=   r;   rB   )r    r1   rE   Úhasattrr[   r^   ÚgetÚemptyÚappendr   r   r*   Úfloat32r'   )ÚclsÚinference_resultr9   rC   r;   Úclass_namesÚ
predictionÚprediction_xyÚprediction_confidenceÚkeypointrB   s              r   Úfrom_inferencezKeyPoints.from_inferenceƒ  s�  € ôV Ð&¬Ô-ÜðYóð ô
 Ð# VÔ,Ø/×4Ñ4À$ÐQUÐ4ÓVÑÜÐ% vÔ.Ø/×4Ñ4Ó6ÐØ×#Ñ# MÔ2Ø—9‘9“;ÐàˆØˆ
ØˆØˆà*¨=Ñ9ò 
	4ˆJØˆMØ$&Ð!Ø& {Ñ3ò E�Ø×$Ñ$ h¨s¡m°X¸c±]Ð%CÔDØ%×,Ñ,¨X°lÑ-CÕDðEð �I‰I�mÔ$Ø×ÑÐ3Ô4à�O‰O˜J zÑ2Ô3Ø×Ñ˜z¨'Ñ2Õ3ð
	4ô "¤2§8¡8¨KÓ#8ð@
ˆñ Ü�x‰x˜¤"§*¡*Ô-Ü "§¡¨¼2¿:¹:Ô FÜ—X‘X˜h¬cÔ2Øô	
ð 	
r   c                ó~  — t        |d«      r[|j                  }t        |j                  t        «      sŒ|j                  €g }n}|j                  j                  D �cg c]  }|‘Œ c}g}nWt        |d«      r|j
                  }n>t        |d«      r2|j                  €g }n#|j                  D �cg c]  }|j                  ‘Œ }}t        «      dk(  r| j                  «       S g }g }|D ]  }g }	g }
|D ]R  }|j                  |d   z  |j                  |d   z  g}|	j                  |«       |
j                  |j                  «       ŒT |j                  |	«       |j                  |
«       Œ�  | t        j                  |t        j                  ¬«      t        j                  |t        j                  ¬«      ¬«      S c c}w c c}w )aš  
        Creates a `sv.KeyPoints` instance from a
        [MediaPipe](https://github.com/google-ai-edge/mediapipe)
        pose landmark detection inference result.

        Args:
            mediapipe_results: The output results from Mediapipe. It supports pose
                and face landmarks from `PoseLandmarker`, `FaceLandmarker` and the
                legacy ones from `Pose` and `FaceMesh`.
            resolution_wh: A tuple of the form `(width, height)` representing the
                resolution of the frame.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates and
                confidences of each keypoint.

        !!! tip
            Before you start, download model bundles from the
            [MediaPipe website](https://ai.google.dev/edge/mediapipe/solutions/vision/pose_landmarker/index#models).

        Examples:
            ```python
            import cv2
            import mediapipe as mp
            import supervision as sv

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            image_height, image_width, _ = image.shape
            mediapipe_image = mp.Image(
                image_format=mp.ImageFormat.SRGB,
                data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

            options = mp.tasks.vision.PoseLandmarkerOptions(
                base_options=mp.tasks.BaseOptions(
                    model_asset_path="pose_landmarker_heavy.task"
                ),
                running_mode=mp.tasks.vision.RunningMode.IMAGE,
                num_poses=2)

            PoseLandmarker = mp.tasks.vision.PoseLandmarker
            with PoseLandmarker.create_from_options(options) as landmarker:
                pose_landmarker_result = landmarker.detect(mediapipe_image)

            key_points = sv.KeyPoints.from_mediapipe(
                pose_landmarker_result, (image_width, image_height))
            ```

            ```python
            import cv2
            import mediapipe as mp
            import supervision as sv

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            image_height, image_width, _ = image.shape
            mediapipe_image = mp.Image(
                image_format=mp.ImageFormat.SRGB,
                data=cv2.cvtColor(image, cv2.COLOR_BGR2RGB))

            options = mp.tasks.vision.FaceLandmarkerOptions(
                base_options=mp.tasks.BaseOptions(
                    model_asset_path="face_landmarker.task"
                ),
                output_face_blendshapes=True,
                output_facial_transformation_matrixes=True,
                num_faces=2)

            FaceLandmarker = mp.tasks.vision.FaceLandmarker
            with FaceLandmarker.create_from_options(options) as landmarker:
                face_landmarker_result = landmarker.detect(mediapipe_image)

            key_points = sv.KeyPoints.from_mediapipe(
                face_landmarker_result, (image_width, image_height))
            ```

        Úpose_landmarksÚface_landmarksÚmulti_face_landmarksr   r   rc   )r9   r=   )re   rs   r    r1   Úlandmarkrt   ru   rQ   rg   r$   ra   rh   Ú
visibilityr   r*   ri   )rj   Úmediapipe_resultsÚresolution_whÚresultsrv   Úface_landmarkr9   rC   Úposern   ro   Úkeypoint_xys               r   Úfrom_mediapipezKeyPoints.from_mediapipe×  sÁ  € ô^ Ð$Ð&6Ô7Ø'×6Ñ6ˆGÜÐ/×>Ñ>ÄÔEØ$×3Ñ3Ð;Ø ‘Gð
 ->×,LÑ,L×,UÑ,Uöà (ò %òð‘Gô Ð&Ð(8Ô9Ø'×6Ñ6‰GÜÐ&Ð(>Ô?Ø ×5Ñ5Ð=Ø‘ð *;×)OÑ)Oöà%ð "×*Ó*ð�ð ô
 ˆw‹<˜1ÒØ—9‘9“;ÐàˆØˆ
Øò 	5ˆDØˆMØ$&Ð!Ø ò B�à—J‘J ¨qÑ!1Ñ1Ø—J‘J ¨qÑ!1Ñ1ð�ð ×$Ñ$ [Ô1Ø%×,Ñ,¨X×-@Ñ-@ÕAðBð �I‰I�mÔ$Ø×ÑÐ3Õ4ð	5ñ Ü�x‰x˜¤"§*¡*Ô-Ü "§¡¨¼2¿:¹:Ô Fô
ð 	
ùòGùòs   Á	F5Â*F:c                óT  — |j                   j                  j                  «       dk(  r| j                  «       S |j                   j                  j	                  «       j                  «       }|j                  j                  j	                  «       j                  «       j                  t        «      }t        j                  |D �cg c]  }|j                  |   ‘Œ c}«      }|j                   j                  j	                  «       j                  «       }t        |i} | ||||¬«      S c c}w )aö  
        Creates a `sv.KeyPoints` instance from a
        [YOLOv8](https://github.com/ultralytics/ultralytics) pose inference result.

        Args:
            ultralytics_results: The output Results instance from YOLOv8.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
                and class names, and confidences of each keypoint.

        Examples:
            ```python
            import cv2
            import supervision as sv
            from ultralytics import YOLO

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = YOLO('yolov8s-pose.pt')

            result = model(image)[0]
            key_points = sv.KeyPoints.from_ultralytics(result)
            ```
        r   )r9   r;   r=   rB   )r`   r9   Únumelrg   ÚcpuÚnumpyÚboxesrj   Úastyper'   r   r*   ÚnamesÚconfr   )rj   Úultralytics_resultsr9   r;   r3   rl   rC   rB   s           r   Úfrom_ultralyticszKeyPoints.from_ultralyticsU  sí   € ð4 ×(Ñ(×+Ñ+×1Ñ1Ó3°qÒ8Ø—9‘9“;Ðà ×*Ñ*×-Ñ-×1Ñ1Ó3×9Ñ9Ó;ˆØ&×,Ñ,×0Ñ0×4Ñ4Ó6×<Ñ<Ó>×EÑEÄcÓJˆÜ—h‘hÀhÖOÀÐ 3× 9Ñ 9¸!Ó <ÒOÓPˆà(×2Ñ2×7Ñ7×;Ñ;Ó=×CÑCÓEˆ
ä! ;ð@
ˆñ �b 8ÀÐRVÔWÐWùò  Ps   ÃD%c                óä  — t        |j                  j                  «      dk(  r| j                  «       S |j                  j                  dd…dd…dd…f   }|j                  j                  dd…dd…df   }t	        |j                  d«      r|j                  j
                  }nd}i }|�>|j                  �2g }|D ]"  }|j                  |   }|j                  |«       Œ$ ||t        <    | ||||¬«      S )aÊ  
        Create a `sv.KeyPoints` instance from a [YOLO-NAS](https://github.com/Deci-AI/super-gradients/blob/master/YOLONAS-POSE.md)
        pose inference results.

        Args:
            yolo_nas_results: The output object from YOLO NAS.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
                and class names, and confidences of each keypoint.

        Examples:
            ```python
            import cv2
            import torch
            import supervision as sv
            import super_gradients

            image = cv2.imread("<SOURCE_IMAGE_PATH>")

            device = "cuda" if torch.cuda.is_available() else "cpu"
            model = super_gradients.training.models.get(
                "yolo_nas_pose_s", pretrained_weights="coco_pose").to(device)

            results = model.predict(image, conf=0.1)
            key_points = sv.KeyPoints.from_yolo_nas(results)
            ```
        r   Né   Úlabelsrd   )	rQ   rm   Úposesrg   re   r‹   rl   rh   r   )	rj   Úyolo_nas_resultsr9   rC   r;   rB   rl   Úc_idÚnames	            r   Úfrom_yolo_naszKeyPoints.from_yolo_nas|  sþ   € ô< Ð×*Ñ*×0Ñ0Ó1°QÒ6Ø—9‘9“;Ðà×(Ñ(×.Ñ.ªq²!°R°a°R¨xÑ8ˆØ%×0Ñ0×6Ñ6²qº!¸Q°wÑ?ˆ
ô Ð#×.Ñ.°Ô9Ø'×2Ñ2×9Ñ9‰HàˆHà?AˆØÐÐ$4×$@Ñ$@Ð$LØˆKØ ò )�Ø'×3Ñ3°DÑ9�Ø×"Ñ" 4Õ(ð)ð +6ˆDÔ&Ñ'áØØ *ØØô	
ð 	
r   c                ó.  — t        |d   d«      r÷|d   j                  j                  «       j                  «       j                  dk(  r| j                  «       S  | |d   j                  j                  «       j                  «       dd…dd…dd…f   |d   j                  j                  «       j                  «       dd…dd…df   |d   j                  j                  «       j                  «       j                  t        «      ¬«      S | j                  «       S )aî  
        Create a `sv.KeyPoints` object from the
        [Detectron2](https://github.com/facebookresearch/detectron2) inference result.

        Args:
            detectron2_results: The output of a
                Detectron2 model containing instances with prediction data.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
                and class names, and confidences of each keypoint.

        Examples:
            ```python
            import cv2
            import supervision as sv
            from detectron2.engine import DefaultPredictor
            from detectron2.config import get_cfg


            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            cfg = get_cfg()
            cfg.merge_from_file("<CONFIG_PATH>")
            cfg.MODEL.WEIGHTS = "<WEIGHTS_PATH>"
            predictor = DefaultPredictor(cfg)

            result = predictor(image)
            keypoints = sv.KeyPoints.from_detectron2(result)
            ```
        Ú	instancesÚpred_keypointsr   NrŠ   ©r9   r=   r;   )	re   r“   r�   r‚   Úsizerg   Úpred_classesr„   r'   )rj   Údetectron2_resultss     r   Úfrom_detectron2zKeyPoints.from_detectron2¶  sâ   € ôB Ð% kÑ2Ð4DÔEØ! +Ñ.×=Ñ=×AÑAÓC×IÑIÓK×PÑPÐTUÒUØ—y‘y“{Ð"ÙØ% kÑ2ß‘§¡£ß‘“ššA˜r ˜r˜ñ#ð %7°{Ñ$Cß‘§¡£ß‘“ššA˜q˜ñ%"ð ,¨KÑ8ß‘Ÿc™c›eß‘“ß‘œ“ôð ð —9‘9“;Ðr   c           	     ó¦  — d|d   v �r5|d   d   j                  «       j                  «       j                  dk(  r| j                  «       S |D �cg c]D  }|d   j                  «       j                  «       |d   j                  «       j                  «       f‘ŒF }}t	        |Ž \  }} | t        j                  |«      j                  t
        j                  «      t        j                  |«      j                  t
        j                  «      t        j                  t        |«      «      j                  t        «      ¬«      S | j                  «       S c c}w )ap	  
        Create a `sv.KeyPoints` object from the
        [Transformers](https://github.com/huggingface/transformers) inference result.

        Args:
            transformers_results: The output of a
                Transformers model containing instances with prediction data.

        Returns:
            A `sv.KeyPoints` object containing the keypoint coordinates, class IDs,
                and class names, and confidences of each keypoint.

        Examples:
            ```python
            from PIL import Image
            import requests
            import supervision as sv
            import torch
            from transformers import (
                AutoProcessor,
                RTDetrForObjectDetection,
                VitPoseForPoseEstimation,
            )

            device = "cuda" if torch.cuda.is_available() else "cpu"
            image = Image.open("<SOURCE_IMAGE_PATH>")

            DETECTION_MODEL_ID = "PekingU/rtdetr_r50vd_coco_o365"

            detection_processor = AutoProcessor.from_pretrained(DETECTION_MODEL_ID, use_fast=True)
            detection_model = RTDetrForObjectDetection.from_pretrained(DETECTION_MODEL_ID, device_map=device)

            inputs = detection_processor(images=frame, return_tensors="pt").to(device)

            with torch.no_grad():
                outputs = detection_model(**inputs)

            target_size = torch.tensor([(frame.height, frame.width)])
            results = detection_processor.post_process_object_detection(
                outputs, target_sizes=target_size, threshold=0.3)

            detections = sv.Detections.from_transformers(results[0])
            boxes = sv.xyxy_to_xywh(detections[detections.class_id == 0].xyxy)

            POSE_ESTIMATION_MODEL_ID = "usyd-community/vitpose-base-simple"

            pose_estimation_processor = AutoProcessor.from_pretrained(POSE_ESTIMATION_MODEL_ID)
            pose_estimation_model = VitPoseForPoseEstimation.from_pretrained(
                POSE_ESTIMATION_MODEL_ID, device_map=device)

            inputs = pose_estimation_processor(frame, boxes=[boxes], return_tensors="pt").to(device)

            with torch.no_grad():
                outputs = pose_estimation_model(**inputs)

            results = pose_estimation_processor.post_process_pose_estimation(outputs, boxes=[boxes])
            key_point = sv.KeyPoints.from_transformers(results[0])
            ```

        r`   r   Úscoresr”   )r�   r‚   r•   rg   Úzipr   Ústackr„   ri   ÚarangerQ   r'   )rj   Útransformers_resultsÚresultÚresult_datar9   rš   s         r   Úfrom_transformerszKeyPoints.from_transformersé  s   € ð~ Ð.¨qÑ1Ò1Ø# AÑ& {Ñ3×7Ñ7Ó9×?Ñ?ÓA×FÑFÈ!ÒKØ—y‘y“{Ð"ð 3öð
 ð ˜;Ñ'×+Ñ+Ó-×3Ñ3Ó5Ø˜8Ñ$×(Ñ(Ó*×0Ñ0Ó2òðˆKð ô ˜kÐ*‰JˆB�áÜ—8‘8˜B“<×&Ñ&¤r§z¡zÓ2Ü$&§H¡H¨VÓ$4×$;Ñ$;¼B¿J¹JÓ$GÜŸ™¤3 r£7Ó+×2Ñ2´3Ó7ôð ð —9‘9“;Ðùò!s   ÁA	Ec                óÈ  — t        | j                  «      }|j                  d   |k7  rt        d|j                  d   › d|› d�«      ‚|j                  d   | j                  j                  d   k7  r6t        d|j                  d   › d| j                  j                  d   › d�«      ‚t	        j
                  |d¬«      }|dkD  r7t	        j                  ||d   k(  «      st        d	|j                  «       › �«      ‚|dkD  rt        |d   «      nd}t	        j                  ||| j                  j                  d
   f| j                  j                  ¬«      }d}| j                  �Vt        t        j                  t        j                     t	        j                  ||f| j                  j                  ¬«      «      }d}| j                   �t	        j                  ||ft"        ¬«      }t%        |«      D ]t  }t	        j&                  ||   «      }	| j                  ||	f   ||<   |� | j                  �| j                  ||	f   ||<   |€ŒT| j                   €Œa| j                   ||	f   ||<   Œv d}
| j(                  �| j(                  j+                  «       }
d}| j,                  �| j,                  j+                  «       }t/        | j0                  t3        d«      «      }t5        |||
|||¬«      S )u×  Filter keypoints using a 2D boolean mask of shape `(n, m)`.

        This method selects the **same set of keypoints from every object**, so
        every row of `mask` must contain the same number of `True` values.  The
        result is a new `KeyPoints` whose keypoint count is that uniform `k`.

        This is suitable for use cases such as *"keep only the left-side joints for
        all persons"* â€” where the selected joint indices are identical across objects.

        It is **not** suitable for per-object confidence filtering
        (`kp[kp.confidence > 0.5]`) when the threshold yields a different number of
        passing keypoints per object, because NumPy cannot represent a ragged
        `(n, ?, 2)` array.  For that pattern either process objects individually or
        zero out low-confidence entries in-place via `kp.confidence`.

        For the single-object case (`n == 1`) any boolean mask always satisfies the
        uniform-count requirement, so `kp[kp.confidence > 0.5]` works as expected.

        Args:
            mask: A boolean array of shape `(n, m)` where `n` is the number of
                objects and `m` is the number of keypoints per object.  Every row
                must select the same number of keypoints so that the result can be
                stored in a uniform `(n, k, ...)` array.

        Returns:
            A new `KeyPoints` instance containing only the keypoints selected by
            the mask for each object.

        Raises:
            ValueError: If `mask.shape[0]` does not match the number of objects, if
                `mask.shape[1]` does not match the number of keypoints, or if
                different rows of the mask select different numbers of `True` values.
        r   z2D boolean mask row count z does not match object count ú.r   z2D boolean mask column count z does not match keypoint count ©Úaxisz®Cannot filter keypoints with a 2D boolean mask where rows have different numbers of True values. All objects must select the same number of keypoints. Got counts per object: rŠ   rc   N©r9   r=   r>   r@   r;   rB   )rQ   r9   ÚshaperE   r   Úsumr2   Útolistr'   Úzerosr,   r=   r
   ÚnptÚNDArrayri   r@   r!   rT   r-   r>   Úcopyr;   r   rB   Úslicer7   )rG   ÚmaskÚnÚcountsÚkÚxy_selectedÚkeypoint_confidence_selectedÚvisible_selectedÚrowÚrow_indicesÚdetection_confidence_selectedÚclass_id_selectedÚdata_selecteds                r   Ú_get_by_2d_bool_maskzKeyPoints._get_by_2d_bool_mask>  sÈ  € ôD �—‘‹LˆØ�:‰:�a‰=˜AÒÜØ,¨T¯Z©Z¸©]¨Oð < Ø !˜s !ð%óð ð �:‰:�a‰=˜DŸG™GŸM™M¨!Ñ,Ò,ÜØ/°·
±
¸1±¨ð ?"Ø"&§'¡'§-¡-°Ñ"2Ð!3°1ð6óð ô —‘˜ 1Ô%ˆØˆqŠ5œŸ™ ¨&°©)Ñ 3Ô4Üð*ð +1¯-©-«/Ð):ð<óð ð   !šeŒC��q‘	ŒN¨ˆÜ—h‘h  1 d§g¡g§m¡m°AÑ&6Ð7¸t¿w¹w¿}¹}ÔMˆØGKÐ$Ø×#Ñ#Ð/Ü+/Ü—‘œBŸJ™JÑ'Ü—‘˜!˜Q˜ t×'?Ñ'?×'EÑ'EÔFó,Ð(ð :>ÐØ�<‰<Ð#Ü!Ÿx™x¨¨A¨´dÔ;ÐÜ˜“8ò 	GˆCÜŸ.™.¨¨c©Ó3ˆKØ#Ÿw™w s¨KÐ'7Ñ8ˆK˜Ñà,Ð8Ø×,Ñ,Ð8à48×4LÑ4LØ˜Ð$ñ5Ð,¨SÑ1ð  Ñ+°·±Ñ0HØ(,¯©°S¸+Ð5EÑ(FÐ  Ò%ð	Gð )-Ð%Ø×$Ñ$Ð0Ø,0×,EÑ,E×,JÑ,JÓ,LÐ)à ÐØ�=‰=Ð$Ø $§¡× 2Ñ 2Ó 4Ðä% d§i¡i´°t³Ó=ˆäØØ <Ø!>Ø$Ø&Øô
ð 	
r   c                óœ	  — t        |t        «      r| j                  j                  |«      S t        |t        j
                  «      r\|j                  dk(  rM|j                  t        k(  r:| j                  t        t        j                  t        j                     |«      «      S t        |t        «      s|t        d«      f}|\  }}t        |t         «      r|g}t        |t"        «      r't%        d„ |D «       «      rt	        j&                  |«      }t        |t"        «      r't%        d„ |D «       «      rt	        j&                  |«      }t        |t        j
                  «      r(|j                  t        k(  rt	        j(                  |«      }t        |t        j
                  «      r(|j                  t        k(  rt	        j(                  |«      }|}t        |t"        t        j
                  f«      rŸt        |t"        t        j
                  f«      rt	        j*                  |«      sjt	        j*                  |«      sUt	        j,                  t        t.        |«      t        t.        |«      «      \  }}t        t.        |«      }t        t.        |«      }t1        |«      }| j2                  ||f   }d}	| j4                  �| j4                  ||f   }	d}
| j6                  �| j6                  |   }
d}| j8                  �| j8                  ||f   }| j:                  �| j:                  |   nd}t=        | j                  t        t.        |«      «      }|j                  dk(  r>|j?                  ddd«      }|	�|	j?                  dd«      }	|��B|j?                  dd«      }�n.|j                  dk(  �rt	        j*                  |d   «      s/t        |d   t        j
                  «      rV|d   j                  dk(  rD|t        j@                  df   }|	�|	t        j@                  df   }	|�©|t        j@                  df   }n“t	        j*                  |d   «      s/t        |d   t        j
                  «      r^|d   j                  dk(  rL|dd…t        j@                  dd…f   }|	�|	dd…t        j@                  f   }	|�|dd…t        j@                  f   }tC        ||	|
|||¬«      S )	a	  
        Get a subset of the KeyPoints object or access an item from its data field.

        Supports detection-level (skeleton) filtering, keypoint-level (anchor)
        filtering, combined tuple indexing, and data field access by string key.

        Args:
            index: The index, indices, or key to access a subset of the KeyPoints
                or an item from the data.

        Returns:
            A subset of the KeyPoints object or an item from the data field.

        Examples:
            ```python
            import supervision as sv

            key_points = sv.KeyPoints(...)

            # detection-level filtering (returns KeyPoints)
            high_conf = key_points[key_points.detection_confidence > 0.5]
            class_0 = key_points[key_points.class_id == 0]

            # keypoint-level filtering (returns KeyPoints)
            visible = key_points[key_points.keypoint_confidence > 0.3]

            # indexing
            first = key_points[0]
            first_two = key_points[0:2]
            subset = key_points[[0, 2]]

            # anchor selection (uniform across all skeletons)
            nose_and_eyes = key_points[:, [0, 1, 2]]

            # data field access
            class_names = key_points['class_name']
            ```
        rŠ   Nc              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­wr   r   r"   s     r   r%   z(KeyPoints.__getitem__.<locals>.<genexpr>Õ  ó   è ø€ Ò&F¸q¤z°!´T×':Ñ&Fùr&   c              3  ó<   K  — | ]  }t        |t        «      –— Œ y ­wr   r   r"   s     r   r%   z(KeyPoints.__getitem__.<locals>.<genexpr>×  r¾   r&   r   r   .r¦   )"r    ÚstrrB   rf   r   r+   r/   r,   r!   r»   r
   r«   r¬   Úbool_Útupler®   r'   r1   r2   r*   r-   ÚisscalarÚix_r   r4   r9   r=   r>   r@   r;   r   r0   Únewaxisr7   )rG   Úindexr3   ÚjÚraw_iÚi_ixÚj_ixÚrow_ir³   r´   r¸   rµ   r¹   rº   s                 r   Ú__getitem__zKeyPoints.__getitem__�  sá  € ôT �eœSÔ!Ø—9‘9—=‘= Ó'Ð'ä�eœRŸZ™ZÔ(¨U¯Z©Z¸1ª_ÀÇÁÔPTÒATØ×,Ñ,¬T´#·+±+¼b¿h¹hÑ2GÈÓ-OÓPÐPä˜%¤Ô'ØœE $›KÐ(ˆEà‰ˆˆ1ä�aœÔØ�ˆAä�aœÔ¤3Ñ&FÀAÔ&FÔ#FÜ—‘˜“ˆAÜ�aœÔ¤3Ñ&FÀAÔ&FÔ#FÜ—‘˜“ˆAä�aœŸ™Ô$¨¯©´DªÜ—‘˜qÓ!ˆAÜ�aœŸ™Ô$¨¯©´DªÜ—‘˜qÓ!ˆAàˆô �qœ4¤§¡Ð,Ô-Ü˜1œt¤R§Z¡ZÐ0Ô1Ü—K‘K ”NÜ—K‘K ”NäŸ™¤¤S¨!£¬d´3¸«lÓ;‰JˆD�$Ü”S˜$“ˆAÜ”S˜$“ˆAä$ UÓ+ˆà—g‘g˜a ˜d‘mˆà'+Ð$Ø×#Ñ#Ð/Ø+/×+CÑ+CÀAÀqÀDÑ+IÐ(à(,Ð%Ø×$Ñ$Ð0Ø,0×,EÑ,EÀeÑ,LÐ)àÐØ�<‰<Ð#Ø#Ÿ|™|¨A¨q¨DÑ1Ðà48·M±MÐ4M˜DŸM™M¨%Ò0ÐSWÐä% d§i¡i´´c¸5Ó1AÓBˆà×Ñ˜qÒ Ø%×-Ñ-¨a°°AÓ6ˆKØ+Ð7Ø/K×/SÑ/SØ�qó0Ð,ð  Ñ+Ø#3×#;Ñ#;¸A¸qÓ#AÒ Ø×Ñ Ó"Ü�{‰{˜5 ™8Ô$Ü˜5 ™8¤R§Z¡ZÔ0°U¸1±X·]±]ÀaÒ5Gà)¬"¯*©*°c¨/Ñ:�Ø/Ð;Ø3OÜŸ
™
 C˜ñ4Ð0ð $Ð/Ø'7¼¿
¹
ÀC¸Ñ'HÑ$Ü—‘˜U 1™XÔ&Ü˜5 ™8¤R§Z¡ZÔ0°U¸1±X·]±]ÀaÒ5Gà)ª!¬R¯Z©ZºÐ*:Ñ;�Ø/Ð;Ø3OÚœ2Ÿ:™:˜ñ4Ð0ð $Ð/Ø'7º¼2¿:¹:¸Ñ'FÐ$äØØ <Ø!>Ø$Ø&Øô
ð 	
r   c                óÂ   — t        |t        j                  t        f«      st	        d«      ‚t        |t        «      rt        j
                  |«      }|| j                  |<   y)a×  
        Set a value in the data dictionary of the `sv.KeyPoints` object.

        Args:
            key: The key in the data dictionary to set.
            value: The value to set for the key.

        Examples:
            ```python
            import cv2
            import supervision as sv
            from ultralytics import YOLO

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = YOLO('yolov8s.pt')

            result = model(image)[0]
            key_points = sv.KeyPoints.from_ultralytics(result)

            key_points['class_name'] = [
                 model.model.names[class_id]
                 for class_id
                 in key_points.class_id
             ]
            ```
        z$Value must be a np.ndarray or a listN)r    r   r+   r1   Ú	TypeErrorr*   rB   )rG   ÚkeyrO   s      r   Ú__setitem__zKeyPoints.__setitem__&  sG   € ô6 ˜%¤"§*¡*¬dÐ!3Ô4ÜÐBÓCÐCä�eœTÔ"Ü—H‘H˜U“OˆEàˆ�	‰	�#Šr   c                óZ   —  | t        j                  dt         j                  ¬«      ¬«      S )aF  
        Create an empty KeyPoints object with no key points.

        Returns:
            An empty `sv.KeyPoints` object.

        Examples:
            ```pycon
            >>> import supervision as sv
            >>> key_points = sv.KeyPoints.empty()
            >>> len(key_points)
            0

            ```
        )r   r   rŠ   rc   )r9   )r   rg   ri   )rj   s    r   rg   zKeyPoints.emptyI  s   € ñ" ”b—h‘h˜y´·
±
Ô;Ô<Ð<r   c                óV   — t         j                  «       }| j                  |_        | |k(  S )ai  
        Returns `True` if the `KeyPoints` object is considered empty.

        Returns:
            `True` if the object is empty, `False` otherwise.

        Example:
            ```pycon
            >>> import supervision as sv
            >>> key_points = sv.KeyPoints.empty()
            >>> key_points.is_empty()
            True

            ```
        )r7   rg   rB   )rG   Úempty_key_pointss     r   Úis_emptyzKeyPoints.is_empty\  s*   € ô  %Ÿ?™?Ó,ÐØ $§	¡	ÐÔØÐ'Ñ'Ð'r   g      à?Fc                óú  — t        | «      dk(  r| S | j                  €t        d«      ‚|s| j                  €t        d«      ‚| j                  }t        j                  |dk(  d¬«       }| j                  �|| j                  z  }t        j                  t        j                  ||d   t
        j                  «      d¬«      }t        j                  t        j                  ||d   t
        j                  «      d¬«      }t        j                  t        j                  ||d   t
        j                   «      d¬«      }t        j                  t        j                  ||d   t
        j                   «      d¬«      }	t        j                  ||||	gd¬«      j                  t
        j                  «      }
|r2t        j                  |
| j                  j!                  dd«      g«      }nwt#        t$        j&                  t
        j(                     | j                  «      }t        j                  |
| j                  j!                  dd«      |j!                  dd«      g«      }t+        |||¬	«      }t#        t,        | |   «      S )
aÎ  
        Performs non-max suppression on the keypoint detections. Bounding boxes
        are derived from valid keypoints of each skeleton, and standard box NMS
        is applied. A keypoint is considered valid when its coordinates are not
        all-zero and its `visible` flag is `True` (if `visible` is set).

        Args:
            threshold: The intersection-over-union threshold to use for
                non-maximum suppression. Must be in [0, 1]. Defaults to 0.5.
            class_agnostic: Whether to perform class-agnostic non-maximum
                suppression. If True, the class_id of each detection will be
                ignored. Defaults to False.
            overlap_metric: Metric used to compute the degree of overlap
                between pairs of bounding boxes. Defaults to
                `OverlapMetric.IOU`.

        Returns:
            A new `sv.KeyPoints` object after non-maximum suppression.

        Raises:
            ValueError: If `detection_confidence` is None.
            ValueError: If `class_agnostic` is False and `class_id`
                is None.

        Examples:
            ```python
            import cv2
            import supervision as sv
            from rfdetr import RFDETRKeypointPreview

            image = cv2.imread("<SOURCE_IMAGE_PATH>")
            model = RFDETRKeypointPreview()

            key_points = model.predict(image)
            key_points = key_points.with_nms(threshold=0.5)
            ```
        r   zDKeyPoints detection_confidence must be given for NMS to be executed.zKeyPoints class_id must be given for NMS to be executed. If you intended to perform class agnostic NMS set class_agnostic=True.éÿÿÿÿr¤   ).r   r   ).r   )r_   Úiou_thresholdÚoverlap_metric)rQ   r>   rE   r;   r9   r   r2   r@   ÚminÚwhereÚinfÚmaxrœ   r„   ri   Úhstackr0   r
   r«   r¬   Úint_r   r7   )rG   Ú	thresholdÚclass_agnosticrØ   r9   ÚvalidÚx_minÚy_minÚx_maxÚy_maxÚxyxyr_   r;   Úkeeps                 r   Úwith_nmszKeyPoints.with_nmsp  sö  € ôV ˆt‹9˜Š>ØˆKà×$Ñ$Ð,ÜØVóð ñ  $§-¡-Ð"7Üð'óð ð �W‰WˆÜ—‘˜˜a™ bÔ)Ð)ˆØ�<‰<Ð#Ø˜DŸL™LÑ(ˆEÜ—‘”r—x‘x  r¨&¡z´2·6±6Ó:ÀÔCˆÜ—‘”r—x‘x  r¨&¡z´2·6±6Ó:ÀÔCˆÜ—‘”r—x‘x  r¨&¡z´B·F±F°7Ó;À!ÔDˆÜ—‘”r—x‘x  r¨&¡z´B·F±F°7Ó;À!ÔDˆÜ�x‰x˜  u¨eÐ4¸1Ô=×DÑDÄRÇZÁZÓPˆáÜŸ)™) T¨4×+DÑ+D×+LÑ+LÈRÐQRÓ+SÐ$TÓU‰KäœCŸK™K¬¯©Ñ0°$·-±-Ó@ˆHÜŸ)™)àØ×-Ñ-×5Ñ5°b¸!Ó<Ø×$Ñ$ R¨Ó+ðóˆKô 'Ø#Ø#Ø)ô
ˆô ”I˜t D™zÓ*Ð*r   c                ó`  — | j                  «       rt        j                  «       S | j                  }|r:t	        j
                  t        |«      t        j                  ¬«      }|dd…|dd…f   }t	        j                  |dk(  d¬«       }|j                  d¬«      }|dd…dd…df   |dd…dd…df   }}t	        j                  ||t        j                  «      j                  d¬«      }t	        j                  ||t        j                  «      j                  d¬«      }	t	        j                  ||t        j                   «      j                  d¬«      }
t	        j                  ||t        j                   «      j                  d¬«      }t	        j                  ||	|
|fd¬«      j                  t        j                   «      }d|| <   | j"                  �*| j"                  j                  t        j                   «      }nU| j$                  �G| j$                  }|r	|dd…f   }|j'                  d¬«      j                  t        j                   «      }nd}t        ||¬«      }| j(                  |_        | j*                  |_        t-        t        |t-        t.        |j0                  «      dkD     «      }|S )	a;  
        Convert a KeyPoints object to a Detections object. This
        approximates the bounding box of the detected object by
        taking the bounding box that fits all key points.

        Args:
            selected_keypoint_indices: The
                indices of the key points to include in the bounding box
                calculation. This helps focus on a subset of key points,
                e.g. when some are occluded. Captures all key points by
                default. An empty sequence (`[]`) is treated the same as
                `None` and selects all key points.

        Returns:
            detections: The converted detections object.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> key_points = sv.KeyPoints(
            ...     xy=np.array([[[10, 20], [30, 40]]], dtype=np.float32)
            ... )
            >>> detections = key_points.as_detections()
            >>> detections.xyxy
            array([[10., 20., 30., 40.]], dtype=float32)

            ```
        rc   Nr   rŠ   r¤   r   g        )ræ   rC   )rÔ   r   rg   r9   r   Úasarrayr1   Úintpr2   ÚanyrÚ   rÛ   rÙ   rÜ   rœ   r„   ri   r>   r=   Úmeanr;   rB   r
   r   Úarea)rG   Úselected_keypoint_indicesr9   Úindicesrá   Ú	has_validr$   ra   râ   rã   rä   rå   ræ   rC   r=   Ú
detectionss                   r   Úas_detectionszKeyPoints.as_detectionsÈ  s"  € ð@ �=‰=Œ?Ü×#Ñ#Ó%Ð%à�W‰WˆÙ$Ü—j‘j¤Ð&?Ó!@ÌÏÉÔPˆGØ’A�w¢�MÑ"ˆBô —‘˜˜a™ aÔ(Ð(ˆØ—I‘I 1�IÓ%ˆ	à’!’Q˜�'‰{˜Bšq¢! Q˜w™Kˆ1ˆÜ—‘˜ ¤2§6¡6Ó*×.Ñ.°AÐ.Ó6ˆÜ—‘˜ ¤2§6¡6Ó*×.Ñ.°AÐ.Ó6ˆÜ—‘˜ ¤B§F¡F 7Ó+×/Ñ/°QÐ/Ó7ˆÜ—‘˜ ¤B§F¡F 7Ó+×/Ñ/°QÐ/Ó7ˆä�x‰x˜  u¨eÐ4¸1Ô=×DÑDÄRÇZÁZÓPˆàˆˆiˆZÑà×$Ñ$Ð0Ø×2Ñ2×9Ñ9¼"¿*¹*ÓE‰JØ×%Ñ%Ð1Ø"&×":Ñ":ÐÙ(Ø&9º!¸W¸*Ñ&EÐ#Ø,×1Ñ1°qÐ1Ó9×@Ñ@ÄÇÁÓL‰JàˆJä T°jÔAˆ
Ø"Ÿm™mˆ
ÔØŸ)™)ˆ
ŒÜœ* j´´c¸:¿?¹?Ó1KÈaÑ1OÑ&PÓQˆ
àÐr   )NNNNN)r9   r8   r;   r:   r=   r<   r>   r<   r@   r?   rB   z5dict[str, npt.NDArray[np.generic] | list[Any]] | NonerC   r<   ÚreturnÚNone)rô   rõ   )rô   r<   )rO   r<   rô   rõ   )rô   r'   )rô   z•Iterator[tuple[npt.NDArray[np.float32], npt.NDArray[np.float32] | None, npt.NDArray[np.int_] | None, dict[str, npt.NDArray[np.generic] | list[Any]]]])rX   Úobjectrô   r!   )rk   r   rô   r7   )rx   r   ry   ztuple[int, int]rô   r7   )r‡   r   rô   r7   )r�   r   rô   r7   )r—   r   rô   r7   )rž   r   rô   r7   )r¯   znpt.NDArray[np.bool_]rô   r7   )rÆ   zIndex1D | Index2D | strrô   z6KeyPoints | npt.NDArray[np.generic] | list[Any] | None)rÏ   rÀ   rO   z#npt.NDArray[np.generic] | list[Any]rô   rõ   )rô   r7   )rô   r!   )rß   Úfloatrà   r!   rØ   r   rô   r7   r   )rï   zIterable[int] | Nonerô   r   )$Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r;   r=   r>   r@   r   r[   rB   rH   rF   ÚpropertyrC   ÚsetterrR   rU   rY   Úclassmethodrq   r~   rˆ   r�   r˜   r¡   r»   rÌ   rÐ   rg   rÔ   r   ÚIOUrè   ró   © r   r   r7   r7   J   sP  … ñ`ðD 	 ÓØ,0€HÐ)Ó0Ø:>ÐÐ7Ó>Ø;?ÐÐ8Ó?Ø,0€GÐ)Ó0Ù;@ÐQUÔ;V€DÐ
8ÓVð
 15Ø>BØ?CØ04ØFJð3ð 6:ñ3à#ð3ð .ð3ð <ð	3ð
 =ð3ð .ð3ð Dð3ð 3ð3ð 
ó3ój
ð ò(ó ð(ð ×Ñò)ó ð)óð(ð
óó0
ð$ òQ
ó ðQ
ðf ð{
Ø #ð{
Ø4Cð{
à	ò{
ó ð{
ðz ò$Xó ð$XðL ò7
ó ð7
ðr ò0ó ð0ðd òRó ðRóh]
ð~G
à&ðG
ð 
@óG
óR!ðF ò=ó ð=ó$(ð, Ø$Ø(5×(9Ñ(9ð	V+àðV+ð ðV+ð &ð	V+ð
 
óV+ðr AEðFØ)=ðFà	ôFr   r7   )r   únpt.NDArray[np.generic] | Noner   r  rô   r!   )r3   Ú_RowIndexInputrô   r)   )3Ú
__future__r   ÚloggingÚcollections.abcr   r   Údataclassesr   r   Útypingr   r	   r
   r‚   r   Únumpy.typingr«   Úsupervision.configr   Úsupervision.detection.corer   Ú$supervision.detection.utils.internalr   r   Ú'supervision.detection.utils.iou_and_nmsr   r   Úsupervision.utils.internalr   Úsupervision.validatorsr   Ú	getLoggerrø   Úloggerr'   r®   r1   r!   r¬   rÞ   rÁ   ÚIndex1DrÂ   ÚIndex2Dr(   Úgenericr  r)   r   r4   r7   r  r   r   ú<module>r     sJ  ðÝ "ã ß .ß (ß #Ñ #ã Ý å 4Ý 1ß M÷õ 7Ý =à	ˆ×	Ñ	˜8Ó	$€à
ØØ	Øˆ�IØˆ�JØ‡K�K�—‘ÑØ‡K�K�—‘Ñðñ€ð �˜Ð Ñ
!€ØØØ‡J�Jˆs�OØ‡K�K�—
‘
ÑØˆ�IØ	ð	ñ€ð ˜CŸK™K¨¯
©
Ñ3°T¸#±YÀÐEÑFÐ ð)Ø)ð)à*ð)ð 
ó)ðØðàóñ. �Ô÷Cð Có ñCr   