Ë
    ¼Ó^j†j  ã                  ó   — d dl mZ 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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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rd dl#Z$e G d„ d«      «       Z% G d„ de«      Z&y)é    )Úannotations)Údeepcopy)Ú	dataclass)ÚTYPE_CHECKINGÚAnyÚcastN)Úpyplot)ÚORIENTED_BOX_COORDINATES)Ú
Detections)Úbox_iou_batchÚmask_iou_batchÚoriented_box_iou_batch)ÚLEGACY_COLOR_PALETTE)ÚMetricÚMetricTarget)ÚObjectSizeCategoryÚget_detection_size_category)Úensure_pandas_installedc                  óº   — e Zd ZU dZded<   edd„«       Zedd„«       Zedd„«       Zded<   ded	<   d
ed<   ded<   d
ed<   ded<   ded<   ded<   dd„Z	dd„Z
dd„Zy)ÚMeanAverageRecallResultux  
    The results of the Mean Average Recall metric calculation.

    Defaults to `0` if no detections or targets were provided.

    Attributes:
        metric_target: the type of data used for the metric -
            boxes, masks or oriented bounding boxes.
        mAR_at_1: the Mean Average Recall, when considering only the top
            highest confidence detection for each class.
        mAR_at_10: the Mean Average Recall, when considering top 10
            highest confidence detections for each class.
        mAR_at_100: the Mean Average Recall, when considering top 100
            highest confidence detections for each class.
        recall_per_class: the recall scores per class and IoU threshold.
            Shape: `(num_target_classes, num_iou_thresholds)`
        max_detections: the array with maximum number of detections
            considered.
        iou_thresholds: the IoU thresholds used in the calculations.
        matched_classes: the class IDs of all matched classes.
            Corresponds to the rows of `recall_per_class`.
        small_objects: the Mean Average Recall
            metric results for small objects (area < 32Â²).
        medium_objects: the Mean Average Recall
            metric results for medium objects (32Â² â‰¤ area < 96Â²).
        large_objects: the Mean Average Recall
            metric results for large objects (area â‰¥ 96Â²).
    r   Úmetric_targetc                ó2   — t        | j                  d   «      S )Nr   ©ÚfloatÚrecall_scores©Úselfs    úr/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/metrics/mean_average_recall.pyÚmAR_at_1z MeanAverageRecallResult.mAR_at_1?   ó   € ä�T×'Ñ'¨Ñ*Ó+Ð+ó    c                ó2   — t        | j                  d   «      S )Né   r   r   s    r   Ú	mAR_at_10z!MeanAverageRecallResult.mAR_at_10C   r    r!   c                ó2   — t        | j                  d   «      S )Né   r   r   s    r   Ú
mAR_at_100z"MeanAverageRecallResult.mAR_at_100G   r    r!   únpt.NDArray[np.float64]r   Úrecall_per_classúnpt.NDArray[np.int32]Úmax_detectionsúnpt.NDArray[np.float32]Úiou_thresholdsÚmatched_classeszMeanAverageRecallResult | NoneÚsmall_objectsÚmedium_objectsÚlarge_objectsc                óü  — | j                   j                  › d| j                  › d| j                  d›d| j                  d›d| j
                  d›d| j                  › d| j                  › d�}| j                  j                  d	k(  r|d
z  }t        | j                  | j                  «      D ]  \  }}|d|› d|› d�z  }Œ d}| j                  �3|t        | j                  «      j                  dd|› �«      z   }|d|› �z  }| j                  �3|t        | j                  «      j                  dd|› �«      z   }|d|› �z  }| j                   �3|t        | j                   «      j                  dd|› �«      z   }|d|› �z  }|S )a  
        Format as a pretty string.

        Example:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> from supervision.metrics import MeanAverageRecall
            >>> predictions = sv.Detections(
            ...     xyxy=np.array([[0, 0, 10, 10]]),
            ...     class_id=np.array([0]),
            ...     confidence=np.array([0.9])
            ... )
            >>> targets = sv.Detections(
            ...     xyxy=np.array([[0, 0, 10, 10]]),
            ...     class_id=np.array([0])
            ... )
            >>> mar_metric = MeanAverageRecall()
            >>> mar_result = mar_metric.update(predictions, targets).compute()
            >>> print(mar_result)  # doctest: +ELLIPSIS
            MeanAverageRecallResult:
            Metric target:  MetricTarget.BOXES
            mAR @ 1:    1.0000
            mAR @ 10:   1.0000
            mAR @ 100:  1.0000
            max detections: [  1  10 100]
            IoU thresh:     [0.5  0.55 ... 0.95]
            mAR per class:
              0: [1. ... 1.]
            ...
            Medium objects:
              MeanAverageRecallResult:
              Metric target:  MetricTarget.BOXES
              mAR @ 1:    0.0000
              ...

            ```
        z:
Metric target:  z
mAR @ 1:    z.4fz
mAR @ 10:   z
mAR @ 100:  z
max detections: z
IoU thresh:     z
mAR per class:
r   z  No results
z  z: ú
z
Small objects:
z
Medium objects:
z
Large objects:
)Ú	__class__Ú__name__r   r   r$   r'   r+   r-   r)   ÚsizeÚzipr.   r/   ÚstrÚreplacer0   r1   )r   Úout_strÚclass_idÚrecall_of_classÚindentÚindenteds         r   Ú__str__zMeanAverageRecallResult.__str__U   sÏ  € ðP �~‰~×&Ñ&Ð'ð (Ø#×1Ñ1Ð2ð 3ØŸ=™=¨Ð-ð .ØŸ>™>¨#Ð.ð /ØŸ?™?¨3Ð/ð 0Ø#×2Ñ2Ð3ð 4Ø#×2Ñ2Ð3ð 4ð ð 	ð × Ñ ×%Ñ%¨Ò*ØÐ'Ñ'ˆGÜ),Ø× Ñ  $×"7Ñ"7ó*
ò 	<Ñ%ˆH�oð ˜˜H˜: R¨Ð'8¸Ð;Ñ;‰Gð	<ð
 ˆØ×ÑÐ)Ø¤ D×$6Ñ$6Ó 7× ?Ñ ?ÀÈÈ6È(ÀmÓ TÑTˆHØÐ+¨H¨:Ð6Ñ6ˆGØ×ÑÐ*Ø¤ D×$7Ñ$7Ó 8× @Ñ @ÀÈÈFÈ8À}Ó UÑUˆHØÐ,¨X¨JÐ7Ñ7ˆGØ×ÑÐ)Ø¤ D×$6Ñ$6Ó 7× ?Ñ ?ÀÈÈ6È(ÀmÓ TÑTˆHØÐ+¨H¨:Ð6Ñ6ˆGàˆr!   c                ó4  — t        «        ddl}| j                  | j                  | j                  dœ}| j
                  �:| j
                  j                  «       }|j                  «       D ]  \  }}||d|› �<   Œ | j                  �:| j                  j                  «       }|j                  «       D ]  \  }}||d|› �<   Œ | j                  �:| j                  j                  «       }|j                  «       D ]  \  }}||d|› �<   Œ  |j                  |dg¬«      S )zt
        Convert the result to a pandas DataFrame.

        Returns:
            The result as a DataFrame.
        r   N©zmAR @ 1zmAR @ 10z	mAR @ 100Úsmall_objects_Úmedium_objects_Úlarge_objects_)Úindex)r   Úpandasr   r$   r'   r/   Ú	to_pandasÚitemsr0   r1   Ú	DataFrame)r   ÚpdÚpandas_dataÚsmall_objects_dfÚkeyÚvalueÚmedium_objects_dfÚlarge_objects_dfs           r   rG   z!MeanAverageRecallResult.to_pandasš   s.  € ô 	 Ô!Ûð —}‘}ØŸ™ØŸ™ñ
ˆð ×ÑÐ)Ø#×1Ñ1×;Ñ;Ó=ÐØ.×4Ñ4Ó6ò <‘
��UØ6;�˜n¨S¨EÐ2Ò3ð<à×ÑÐ*Ø $× 3Ñ 3× =Ñ =Ó ?ÐØ/×5Ñ5Ó7ò =‘
��UØ7<�˜o¨c¨UÐ3Ò4ð=à×ÑÐ)Ø#×1Ñ1×;Ñ;Ó=ÐØ.×4Ñ4Ó6ò <‘
��UØ6;�˜n¨S¨EÐ2Ò3ð<ð ˆr�|‰|˜K°¨sÔ3Ð3r!   c                ó   — g d¢}| j                   | j                  | j                  g}t        d   gdz  }| j                  �I| j                  }|g d¢z  }||j                   |j                  |j                  gz  }|t        d   gdz  z  }| j
                  �I| j
                  }|g d¢z  }||j                   |j                  |j                  gz  }|t        d   gdz  z  }| j                  �I| j                  }|g d¢z  }||j                   |j                  |j                  gz  }|t        d	   gdz  z  }d
t        j                  d<   t        j                  d¬«      \  }}|j                  dd«       |j                  dd¬«       d| j                  j                  › d�}	|j                  |	d¬«       t        t!        |«      «      }
|j#                  |
||d¬«      }|j%                  |
«       |j'                  |dd¬«       |D ]O  }|j)                  «       }|j+                  |j-                  «       |j/                  «       dz  z   |dz   |d›dd¬«       ŒQ dt        j                  d<   t        j0                  «        t        j2                  «        y)zÎ
        Plot the Mean Average Recall results.

        ![example_plot](            https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png            ){ align=center width="800" }
        rA   r   é   N)zSmall: mAR @ 1zSmall: mAR @ 10zSmall: mAR @ 100)zMedium: mAR @ 1zMedium: mAR @ 10zMedium: mAR @ 100r&   )zLarge: mAR @ 1zLarge: mAR @ 10zLarge: mAR @ 100é   Ú	monospacezfont.family)é
   é   )Úfigsizer#   ÚValueÚbold)Ú
fontweightz-Mean Average Recall, by Object Size
(target: ú)Úcenter)ÚcolorÚaligné-   Úright)ÚrotationÚhag{®Gáz”?z.2fÚbottom)rb   Úvaz
sans-serif)r   r$   r'   r   r/   r0   r1   ÚpltÚrcParamsÚsubplotsÚset_ylimÚ
set_ylabelr   rN   Ú	set_titleÚrangeÚlenÚbarÚ
set_xticksÚset_xticklabelsÚ
get_heightÚtextÚget_xÚ	get_widthÚtight_layoutÚshow)r   ÚlabelsÚvaluesÚcolorsr/   r0   r1   Ú_ÚaxÚtitleÚx_positionsÚbarsrm   Úy_values                 r   ÚplotzMeanAverageRecallResult.plot¹   s—  € ò 6ˆØ—-‘- §¡°·±ÐAˆÜ& qÑ)Ð*¨QÑ.ˆà×ÑÐ)Ø ×.Ñ.ˆMØÒOÑOˆFØØ×&Ñ&Ø×'Ñ'Ø×(Ñ(ðñ ˆFð
 Ô+¨AÑ.Ð/°!Ñ3Ñ3ˆFà×ÑÐ*Ø!×0Ñ0ˆNØÒRÑRˆFØØ×'Ñ'Ø×(Ñ(Ø×)Ñ)ðñ ˆFð
 Ô+¨AÑ.Ð/°!Ñ3Ñ3ˆFà×ÑÐ)Ø ×.Ñ.ˆMØÒOÑOˆFØØ×&Ñ&Ø×'Ñ'Ø×(Ñ(ðñ ˆFð
 Ô+¨AÑ.Ð/°!Ñ3Ñ3ˆFà&1Œ�‰�]Ñ#ä—‘ WÔ-‰ˆˆ2Ø
�‰�A�qÔØ
�‰�g¨&ˆÔ1à<¸T×=OÑ=O×=UÑ=UÐ<VÐVWÐXð 	ð 	�‰�U vˆÔ.äœC ›KÓ(ˆØ�v‰v�k 6°¸xˆvÓHˆà
�‰�kÔ"Ø
×Ñ˜6¨B°7ÐÔ;àò 	ˆCØ—n‘nÓ&ˆGØ�G‰GØ—	‘	“˜cŸm™m›o°Ñ1Ñ1Ø˜$‘Ø˜3�-ØØð õ ð	ð '3Œ�‰�]Ñ#ä×ÑÔÜ�‰�
r!   N)Úreturnr   )r€   r8   )r€   zpd.DataFrame©r€   ÚNone)r5   Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__Úpropertyr   r$   r'   r?   rG   r   © r!   r   r   r      s�   … ñð:  Óàò,ó ð,ð ò,ó ð,ð ò,ó ð,ð +Ó*Ø-Ó-Ø)Ó)Ø+Ó+Ø*Ó*à1Ó1Ø2Ó2Ø1Ó1óCóJ4ô>Gr!   r   c                  ó(  — e Zd ZdZej
                  f	 dd„Zdd„Z	 	 	 	 	 	 dd„Zdd„Z		 	 	 	 	 	 dd„Z
	 	 	 	 	 	 	 	 	 	 dd„Ze	 	 	 	 	 	 	 	 	 	 dd„«       Ze	 	 	 	 	 	 	 	 	 	 dd	„«       Ze	 	 	 	 dd
„«       Zdd„Zdd„Z	 	 	 	 	 	 dd„Z	 	 	 	 	 	 	 	 dd„Zy)ÚMeanAverageRecalla<  
    Mean Average Recall (mAR) measures how well the model detects
    and retrieves relevant objects by averaging recall over multiple
    IoU thresholds, classes and detection limits.

    Intuitively, while Recall measures the ability to find all relevant
    objects, mAR narrows down how many detections are considered for each
    class. For example, mAR @ 100 considers the top 100 highest confidence
    detections for each class. mAR @ 1 considers only the highest
    confidence detection for each class.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from supervision.metrics import MeanAverageRecall
        >>> predictions = sv.Detections(
        ...     xyxy=np.array([[0, 0, 10, 10]]),
        ...     class_id=np.array([0]),
        ...     confidence=np.array([0.9])
        ... )
        >>> targets = sv.Detections(
        ...     xyxy=np.array([[0, 0, 10, 10]]),
        ...     class_id=np.array([0])
        ... )
        >>> mar_metric = MeanAverageRecall()
        >>> mar_result = mar_metric.update(predictions, targets).compute()
        >>> round(float(mar_result.mAR_at_100), 2)
        1.0

        ```

    ![example_plot](
        https://media.roboflow.com/supervision-docs/metrics/mAR_plot_example.png
    ){ align=center width="800" }
    c                óf   — || _         g | _        g | _        t        j                  g d¢«      | _        y)z‰
        Initialize the Mean Average Recall metric.

        Args:
            metric_target: The type of detection data to use.
        )r#   rU   éd   N)Ú_metric_targetÚ_predictions_listÚ_targets_listÚnpÚarrayr+   )r   r   s     r   Ú__init__zMeanAverageRecall.__init__)  s-   € ð ,ˆÔà35ˆÔØ/1ˆÔä Ÿh™h¢|Ó4ˆÕr!   c                ó    — g | _         g | _        y)zR
        Reset the metric to its initial state, clearing all stored data.
        N)rŽ   r�   r   s    r   ÚresetzMeanAverageRecall.reset:  s   € ð "$ˆÔØˆÕr!   c                ó4  — t        |t        «      s|g}t        |t        «      s|g}t        |«      t        |«      k7  r$t        dt        |«      › dt        |«      › d�«      ‚| j                  j                  |«       | j                  j                  |«       | S )a  
        Add new predictions and targets to the metric, but do not compute the result.

        Args:
            predictions: The predicted detections.
            targets: The target detections.

        Returns:
            The updated metric instance.
        zThe number of predictions (z) and targets (z%) during the update must be the same.)Ú
isinstanceÚlistrl   Ú
ValueErrorrŽ   Úextendr�   )r   ÚpredictionsÚtargetss      r   ÚupdatezMeanAverageRecall.updateA  s˜   € ô ˜+¤tÔ,Ø&˜-ˆKÜ˜'¤4Ô(Ø�iˆGäˆ{Óœs 7›|Ò+ÜØ-¬c°+Ó.>Ð-?ð @Ü  ›\˜NÐ*OðQóð ð
 	×Ñ×%Ñ% kÔ2Ø×Ñ×!Ñ! 'Ô*àˆr!   c                ó,  — | j                  | j                  | j                  «      }| j                  | j                  | j                  t        j
                  «      \  }}| j                  ||«      |_        | j                  | j                  | j                  t        j                  «      \  }}| j                  ||«      |_        | j                  | j                  | j                  t        j                  «      \  }}| j                  ||«      |_
        |S )zó
        Calculate the Mean Average Recall metric based on the stored predictions
        and ground-truth, at different IoU thresholds and maximum detection counts.

        Returns:
            The Mean Average Recall metric result.
        )Ú_computerŽ   r�   Ú'_filter_predictions_and_targets_by_sizer   ÚSMALLr/   ÚMEDIUMr0   ÚLARGEr1   )r   ÚresultÚsmall_predictionsÚsmall_targetsÚmedium_predictionsÚmedium_targetsÚlarge_predictionsÚlarge_targetss           r   ÚcomputezMeanAverageRecall.compute`  sû   € ð —‘˜t×5Ñ5°t×7IÑ7IÓJˆà+/×+WÑ+WØ×"Ñ" D×$6Ñ$6Ô8J×8PÑ8Pó,
Ñ(Ð˜=ð  $Ÿ}™}Ð->ÀÓNˆÔð ×8Ñ8Ø×&Ñ&¨×(:Ñ(:Ô<N×<UÑ<Uóñ 	+Ð˜Nð
 !%§¡Ð.@À.Ó QˆÔà+/×+WÑ+WØ×"Ñ" D×$6Ñ$6Ô8J×8PÑ8Pó,
Ñ(Ð˜=ð  $Ÿ}™}Ð->ÀÓNˆÔàˆr!   c                óZ  — t        j                  ddd«      }g }t        ||«      D �]•  \  }}| j                  |«      }| j                  |«      }t	        |«      dkD  sŒ8t	        |«      dk(  rw|j                  t        j                  d|j                  ft        ¬«      t        j                  dt        ¬«      t        j                  dt        ¬«      |j                  f«       Œ½| j                  t        j                  k(  rt        ||«      }	n_| j                  t        j                  k(  rt!        ||«      }	n5| j                  t        j"                  k(  rt%        ||«      }	nt'        d«      ‚| j)                  |j                  �|j                  nt        j*                  g «      |j                  �|j                  nt        j*                  g «      |	|«      }
t        j,                  t/        t0        j2                  t         j4                     |j6                  «       «      }|j                  |
|   t        j8                  t	        |«      «      t/        t0        j2                  t         j:                     |j                  «      |   t/        t0        j2                  t         j:                     |j                  «      f«       �Œ˜ |sƒt=        | j                  t        j                  |j>                  d   «      t        j                  d|j>                  d   f«      | j@                  |t        j*                  g t        ¬«      d d d ¬«	      S t        |Ž D �cg c]  }t        jB                  |d«      ‘Œ }} | jD                  |Ž \  }}}t=        | j                  ||| j@                  ||d d d ¬«	      S c c}w )	Ng      à?gffffffî?rU   r   ©Údtype)r   z-Unsupported metric target for IoU calculation)	r   r   r)   r+   r-   r.   r/   r0   r1   )#r�   Úlinspacer7   Ú_detections_contentrl   ÚappendÚzerosr6   ÚboolÚintr;   r�   r   ÚBOXESr   ÚMASKSr   ÚORIENTED_BOUNDING_BOXESr   r˜   Ú_match_detection_batchr‘   Úargsortr   ÚnptÚNDArrayÚfloat32Ú
confidenceÚarangeÚint32r   Úshaper+   ÚconcatenateÚ#_compute_average_recall_for_classes)r   Úpredictions_listÚtargets_listr-   Ústatsrš   r›   Úprediction_contentsÚtarget_contentsÚiouÚmatchesÚsorted_indicesrH   Úconcatenated_statsÚrecall_scores_per_kr)   Úunique_classess                    r   rž   zMeanAverageRecall._compute}  s*  € ô Ÿ™ S¨$°Ó3ˆØˆä$'Ð(8¸,Ó$Gó 4	Ñ ˆK˜Ø"&×":Ñ":¸;Ó"GÐØ"×6Ñ6°wÓ?ˆOä�7‹|˜aÓÜ�{Ó# qÒ(Ø—L‘LäŸH™H a¨×)<Ñ)<Ð%=ÄTÔJÜŸH™H T´Ô5ÜŸH™H T´Ô5Ø#×,Ñ,ð	õð ×*Ñ*¬l×.@Ñ.@Ò@Ü+¨OÐ=PÓQ™Ø×,Ñ,´×0BÑ0BÒBÜ,¨_Ð>QÓR™Ø×,Ñ,´×0TÑ0TÒTÜ4Ø+Ð-@ó™ô )ØKóð ð #×9Ñ9à&×/Ñ/Ð;ð $×,Ò,äŸX™X b›\à"×+Ñ+Ð7ð  ×(Ò(äŸX™X b›\ØØ&ó	�Gô &(§Z¡ZÜœcŸk™k¬"¯*©*Ñ5°{×7MÑ7MÓNÐNó&�Nð —L‘Là# NÑ3ÜŸI™I¤c¨+Ó&6Ó7Ü ¤§¡¬R¯X©XÑ!6¸×8LÑ8LÓMØ .ñô !¤§¡¬R¯X©XÑ!6¸×8HÑ8HÓIðö	ðW4	ñl Ü*Ø"×1Ñ1Ü Ÿh™h ~×';Ñ';¸AÑ'>Ó?Ü!#§¡¨1¨n×.BÑ.BÀ1Ñ.EÐ*FÓ!GØ#×2Ñ2Ø-Ü "§¡¨´3Ô 7Ø"Ø#Ø"ô
ð 
ô EHÈÀKÖP¸5œbŸn™n¨U°AÕ6ÐPÐÐPà4ˆD×4Ñ4Ð6HÐIñ 	>ÐÐ-¨~ô 'Ø×-Ñ-Ø-Ø-Ø×.Ñ.Ø)Ø*ØØØô

ð 
	
ùò Qs   ÍN(c                óp  — t        j                  |d¬«      \  }}g }| j                  D ]D  }| j                  |||k     |||k     ||«      }	| j	                  |	«      }
|j                  |
«       ŒF t        j                  |«      }t        j                  |d¬«      }t        j                  |d¬«      }|
|fS )NT)Úreturn_countsr&   ©Úaxisr#   )r�   Úuniquer+   Ú_compute_confusion_matrixÚ_compute_recallr°   r‘   Úmean)r   rÈ   Úprediction_indicesÚprediction_class_idsÚtrue_class_idsrÌ   Úclass_countsÚrecalls_at_kr+   Úconfusion_matrixr)   Úaverage_recall_per_classr   s                r   rÁ   z5MeanAverageRecall._compute_average_recall_for_classes×  sË   € ô (*§y¡y°ÈtÔ'TÑ$ˆ˜àˆØ"×1Ñ1ò 	2ˆNà#×=Ñ=ØÐ*¨^Ñ;Ñ<Ø$Ð%7¸.Ñ%HÑIØØó	 Ðð  $×3Ñ3Ð4DÓEÐØ×ÑÐ 0Õ1ð	2ô —x‘x Ó-ˆÜ#%§7¡7¨<¸aÔ#@Ð ô Ÿ™Ð 8¸qÔAˆàÐ.°Ð>Ð>r!   c                óÎ  — | j                   d   |j                   d   }}t        j                  ||ft        ¬«      }|d d …d f   | k(  }t	        |«      D �]  \  }}	t        j
                  ||	k\  |z  «      }
|
d   j                   d   sŒ5t        j                  |
d¬«      }||
   d d …d f   }t        j                  ||g«      }|
d   j                   d   dkD  rh||d d …df   j                  «       d d d…      }|t        j                  |d d …df   d¬«      d      }|t        j                  |d d …df   d¬«      d      }d||d d …df   j                  t        «      |f<   �Œ |}|S )	Nr   r¬   r#   rÏ   r&   éÿÿÿÿT)Úreturn_index)r¿   r�   r±   r²   Ú	enumerateÚwhereÚstackÚhstackr¸   rÑ   Úastyper³   )Úpredictions_classesÚtarget_classesrÇ   r-   Únum_predictionsÚnum_iou_levelsÚcorrectÚcorrect_classÚiÚ	iou_levelÚmatched_indicesÚcombined_indicesÚ
iou_valuesrÈ   Úresult_corrects                  r   r·   z(MeanAverageRecall._match_detection_batchû  s~  € ð  ×%Ñ% aÑ(Ø× Ñ  Ñ#ð (ˆô —(‘(˜O¨^Ð<ÄDÔIˆØ&¢q¨$ wÑ/Ð3FÑFˆä% nÓ5ó 	=‰LˆAˆyÜ Ÿh™h¨¨yÑ(8¸MÑ'IÓJˆOà˜qÑ!×'Ñ'¨Ó*Ü#%§8¡8¨OÀ!Ô#DÐ Ø  Ñ1²!°T°'Ñ:�
ÜŸ)™)Ð%5°zÐ$BÓC�à" 1Ñ%×+Ñ+¨AÑ.°Ò2Ø% gªa°¨d¡m×&;Ñ&;Ó&=¹dÀ¸dÑ&CÑD�GØ%¤b§i¡i°º¸1¸±ÈDÔ&QÐRSÑ&TÑU�GØ%¤b§i¡i°º¸1¸±ÈDÔ&QÐRSÑ&TÑU�Gà8<�˜¢ 1 ™×,Ñ,¬SÓ1°1Ð4Ó5ð	=ð 18ˆØÐr!   c                ó   — | j                   d   }|j                   d   }t        j                  ||dft        j                  ¬«      }t	        |«      D ]÷  \  }}||k(  }	||   }
|	j                  «       }|dk(  rAt        j                  |«      }t        j                  |«      }t        j                  ||
«      }nu|
dk(  rAt        j                  |«      }t        j                  ||«      }t        j                  |«      }n/| |	   }|j                  d«      }d|z
  j                  d«      }|
|z
  }t        j                  |||gd¬«      ||<   Œù |}|S )a  
        Compute the confusion matrix for each class and IoU threshold.

        Assumes the matches and prediction_class_ids are sorted by confidence
        in descending order.

        Args:
            sorted_matches: shape (P, Th), that is True
                if the prediction is a true positive at the given IoU threshold.
            sorted_prediction_class_ids: shape (P,), containing
                the class id for each prediction.
            unique_classes: shape (C,), containing the unique
                class ids.
            class_counts: shape (C,), containing the number
                of true instances for each class.
            max_detections: The maximum number of detections to
                consider for each class. Extra detections are considered false
                positives. By default, all detections are considered.

        Returns:
            shape (C, Th, 3), containing the true positives, false
                positives, and false negatives for each class and IoU threshold.
        r#   r   rR   r¬   rÏ   )r¿   r�   r±   Úfloat64rß   ÚsumÚfullrá   )Úsorted_matchesÚsorted_prediction_class_idsrÌ   rØ   Únum_thresholdsÚnum_classesrÚ   Ú	class_idxr;   Úis_classÚnum_trueræ   Útrue_positivesÚfalse_positivesÚfalse_negativesÚlimited_matchesÚresult_confusion_matrixs                    r   rÒ   z+MeanAverageRecall._compute_confusion_matrix  sL  € ð< (×-Ñ-¨aÑ0ˆØ$×*Ñ*¨1Ñ-ˆä46·H±HØ˜.¨!Ð,´B·J±Jô5
Ðô $-¨^Ó#<ò 	ÑˆI�xØ2°hÑ>ˆHØ# IÑ.ˆHØ&Ÿl™l›nˆOà !Ò#Ü!#§¡¨.Ó!9�Ü"$§(¡(¨>Ó":�Ü"$§'¡'¨.¸(Ó"C‘Ø˜Q’Ü!#§¡¨.Ó!9�Ü"$§'¡'¨.¸/Ó"J�Ü"$§(¡(¨>Ó":‘à"0°Ñ":�Ø!0×!4Ñ!4°QÓ!7�à#$ Ñ#6×";Ñ";¸AÓ">�Ø"*¨^Ñ";�ä*,¯(©(Ø °/ÐBÈô+Ð˜YÒ'ð)	ð0 <LÐØ&Ð&r!   c                ó¶   — | j                   d   dk(  st        d| j                   › �«      ‚| d   }| d   }||z   }t        j                  |dk(  d||z  «      }|}|S )a[  
        Broadcastable function, computing the recall from the confusion matrix.

        Args:
            confusion_matrix: shape (N, ..., 3), where the last dimension
                contains the true positives, false positives, and false negatives.

        Returns:
            shape (N, ...), containing the recall for each element.
        rÝ   rR   z/Confusion matrix must have shape (..., 3), got ).r   ).r&   r   )r¿   r˜   r�   rà   )rÚ   rû   rý   ÚdenominatorÚrecallÚresult_recalls         r   rÓ   z!MeanAverageRecall._compute_recallY  s   € ð  ×%Ñ% bÑ)¨QÒ.ÜØAØ#×)Ñ)Ð*ð,óð ð *¨&Ñ1ˆØ*¨6Ñ2ˆà$ Ñ6ˆÜ—‘˜+¨Ñ*¨A¨~ÀÑ/KÓLˆà17ˆØÐr!   c                ó  — | j                   t        j                  k(  r|j                  }|S | j                   t        j                  k(  r*|j
                  �|j
                  }|S | j                  «       S | j                   t        j                  k(  rf|j                  j                  t        «      }|�5t        |«      dkD  r't        j                  |t        j                  ¬«      }|S | j                  «       S t        d| j                   › �«      ‚)z?Return boxes, masks or oriented bounding boxes from detections.r   r¬   úInvalid metric target: )r�   r   r´   Úxyxyrµ   ÚmaskÚ_make_empty_contentr¶   ÚdataÚgetr
   rl   r�   r‘   r»   r˜   )r   Ú
detectionsÚresult_boxesÚresult_masksÚobbÚ
result_obbs         r   r¯   z%MeanAverageRecall._detections_contentu  sÜ   € à×Ñ¤,×"4Ñ"4Ò4Ø4>·O±OˆLØÐØ×Ñ¤,×"4Ñ"4Ò4Ø�‰Ð*Ø6@·o±o�Ø#Ð#Ø×+Ñ+Ó-Ð-Ø×Ñ¤,×"FÑ"FÒFØ—/‘/×%Ñ%Ô&>Ó?ˆCØˆ¤3 s£8¨a¢<Ü68·h±h¸sÌ"Ï*É*Ô6U�
Ø!Ð!Ø×+Ñ+Ó-Ð-ÜÐ2°4×3FÑ3FÐ2GÐHÓIÐIr!   c                ó¶  — | j                   t        j                  k(  r't        j                  dt        j
                  ¬«      }|S | j                   t        j                  k(  rt        j                  dt        ¬«      }|S | j                   t        j                  k(  r't        j                  dt        j
                  ¬«      }|S t        d| j                   › �«      ‚)N)r   rS   r¬   )r   r   r   )r   rS   r&   r  )
r�   r   r´   r�   Úemptyr»   rµ   r²   r¶   r˜   )r   Úempty_boxesÚempty_masksÚ	empty_obbs       r   r  z%MeanAverageRecall._make_empty_content‡  s¢   € Ø×Ñ¤,×"4Ñ"4Ò4Ü35·8±8¸FÌ"Ï*É*Ô3UˆKØÐà×Ñ¤,×"4Ñ"4Ò4Ü13·±¸)Ì4Ô1PˆKØÐà×Ñ¤,×"FÑ"FÒFÜ13·±¸)Ì2Ï:É:Ô1VˆIØÐäÐ2°4×3FÑ3FÐ2GÐHÓIÐIr!   c                ó~  — t        |«      }|j                  «       s|t        j                  k(  r|S t	        || j
                  «      }||j                  k(  }|j                  |   |_        |j                  �|j                  |   |_        |j                  �|j                  |   |_	        |j                  �|j                  |   |_
        |j                  �|j                  |   |_        |j                  �G|j                  j                  «       D ]*  \  }}t        j                  |«      |   |j                  |<   Œ, |S )zBReturn a copy of detections with contents filtered by object size.)r   Úis_emptyr   ÚANYr   r�   rN   r  r  r;   r¼   Ú
tracker_idr	  rH   r�   r‘   )r   r  Úsize_categoryÚnew_detectionsÚsizesÚ	size_maskrM   rN   s           r   Ú_filter_detections_by_sizez,MeanAverageRecall._filter_detections_by_size–  s4  € ô " *Ó-ˆØ×ÑÔ  MÔ5G×5KÑ5KÒ$KØ!Ð!ä+¨N¸D×<OÑ<OÓPˆØ˜]×0Ñ0Ñ0ˆ	à,×1Ñ1°)Ñ<ˆÔØ×ÑÐ*Ø"0×"5Ñ"5°iÑ"@ˆNÔØ×"Ñ"Ð.Ø&4×&=Ñ&=¸iÑ&HˆNÔ#Ø×$Ñ$Ð0Ø(6×(AÑ(AÀ)Ñ(LˆNÔ%Ø×$Ñ$Ð0Ø(6×(AÑ(AÀ)Ñ(LˆNÔ%Ø×ÑÐ*Ø,×1Ñ1×7Ñ7Ó9ò F‘
��UÜ+-¯8©8°E«?¸9Ñ+E�×#Ñ# CÒ(ðFð Ðr!   c                ó¾   — g }g }t        ||«      D ]G  \  }}|j                  | j                  ||«      «       |j                  | j                  ||«      «       ŒI ||fS )zI
        Filter predictions and targets by object size category.
        )r7   r°   r  )r   rÂ   rÃ   r  Únew_predictions_listÚnew_targets_listrš   r›   s           r   rŸ   z9MeanAverageRecall._filter_predictions_and_targets_by_size°  sx   € ð  "ÐØÐÜ$'Ð(8¸,Ó$Gò 	Ñ ˆK˜Ø ×'Ñ'Ø×/Ñ/°¸]ÓKôð ×#Ñ#Ø×/Ñ/°¸ÓGõð		ð $Ð%5Ð5Ð5r!   N)r   r   r�   )rš   úDetections | list[Detections]r›   r!  r€   rŠ   )r€   r   )rÂ   úlist[Detections]rÃ   r"  r€   r   )
rÈ   únpt.NDArray[np.bool_]rÕ   r*   rÖ   r*   r×   r*   r€   zNtuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.int32]])
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  r   r€   únpt.NDArray[Any])r€   r$  )r  r   r  r   r€   r   )rÂ   r"  rÃ   r"  r  r   r€   z)tuple[list[Detections], list[Detections]])r5   rƒ   r„   r…   r   r´   r’   r”   rœ   rª   rž   rÁ   Ústaticmethodr·   rÒ   rÓ   r¯   r  r  rŸ   rˆ   r!   r   rŠ   rŠ     s   „ ñ#ðN '3×&8Ñ&8ð5à#ó5ó" ðà2ðð /ðð 
ó	ó>ð:X
Ø 0ðX
Ø@PðX
à	 óX
ðt"?à&ð"?ð 2ð"?ð 4ð	"?ð
 .ð"?ð
ó"?ðH ðØ2ðà-ðð %ðð 0ð	ð
 
òó ðð< ð<'Ø-ð<'à%:ð<'ð .ð<'ð ,ð	<'ð
 
!ò<'ó ð<'ð| ðØ1ðà	 òó ðó6Jó$JðØ$ðØ5Gðà	óð46à*ð6ð 'ð6ð *ð	6ð
 
3ô6r!   rŠ   )'Ú
__future__r   Úcopyr   Údataclassesr   Útypingr   r   r   Únumpyr�   Únumpy.typingr¹   Ú
matplotlibr	   re   Úsupervision.configr
   Úsupervision.detection.corer   Ú'supervision.detection.utils.iou_and_nmsr   r   r   Úsupervision.draw.colorr   Úsupervision.metrics.corer   r   Ú%supervision.metrics.utils.object_sizer   r   Úsupervision.metrics.utils.utilsr   rF   rJ   r   rŠ   rˆ   r!   r   ú<module>r4     sq   ðÝ "å Ý !ß +Ñ +ã Ý Ý $å 7Ý 1÷ñ õ
 8ß 9÷õ DáÛð ÷að aó ðaôH6˜õ 6r!   