Ë
    ¼Ó^jr  ã                  ó   — 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	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mZ d dlmZm Z  d dl!m"Z" erd dl#Z$ G d„ de«      Z%e G d„ d«      «       Z&y)é    )Úannotations)Údeepcopy)Ú	dataclass)ÚTYPE_CHECKINGÚAnyN)Úpyplot)ÚORIENTED_BOX_COORDINATES)Ú
Detections)Úbox_iou_batchÚmask_iou_batchÚoriented_box_iou_batch)ÚLEGACY_COLOR_PALETTE)ÚAveragingMethodÚMetricÚMetricTarget)ÚObjectSizeCategoryÚget_detection_size_category)Úensure_pandas_installedc                  óB  — e Zd ZdZej
                  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)Ú	Precisiona/  
    Precision is a metric used to evaluate object detection models. It is the ratio of
    true positive detections to the total number of predicted detections. We calculate
    it at different IoU thresholds.

    In simple terms, Precision is a measure of a model's accuracy, calculated as:

    `Precision = TP / (TP + FP)`

    Here, `TP` is the number of true positives (correct detections), and `FP` is the
    number of false positive detections (detected, but incorrectly).

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> from supervision.metrics import Precision
        >>> 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])
        ... )
        >>> precision_metric = Precision()
        >>> precision_result = precision_metric.update(predictions, targets).compute()
        >>> round(float(precision_result.precision_at_50), 2)
        1.0

        ```

    ![example_plot](
        https://media.roboflow.com/supervision-docs/metrics/precision_plot_example.png
    ){ align=center width="800" }
    c                ó<   — || _         || _        g | _        g | _        y)a  
        Initialize the Precision metric.

        Args:
            metric_target: The type of detection data to use.
            averaging_method: The averaging method used to compute the
                precision. Determines how the precision is aggregated across classes.
        N)Ú_metric_targetÚaveraging_methodÚ_predictions_listÚ_targets_list)ÚselfÚmetric_targetr   s      úh/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/metrics/precision.pyÚ__init__zPrecision.__init__E   s$   € ð ,ˆÔØ 0ˆÔà35ˆÔØ/1ˆÕó    c                ó    — g | _         g | _        y)zR
        Reset the metric to its initial state, clearing all stored data.
        N)r   r   ©r   s    r   ÚresetzPrecision.resetX   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ÚlistÚlenÚ
ValueErrorr   Úextendr   )r   ÚpredictionsÚtargetss      r   ÚupdatezPrecision.update_   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 precision metric based on the stored predictions and ground-truth
        data, at different IoU thresholds.

        Returns:
            The precision metric result.
        )Ú_computer   r   Ú'_filter_predictions_and_targets_by_sizer   ÚSMALLÚsmall_objectsÚMEDIUMÚmedium_objectsÚLARGEÚlarge_objects)r   ÚresultÚsmall_predictionsÚsmall_targetsÚmedium_predictionsÚmedium_targetsÚlarge_predictionsÚlarge_targetss           r   ÚcomputezPrecision.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                ó~  — t        j                  ddd«      }g }t        ||«      D �]§  \  }}| j                  |«      }| j                  |«      }t	        |«      dk(  r¬t	        |«      dkD  rž|j
                  �|j                  €Œ^|j                  t        j                  t	        |«      |j                  ft         j                  ¬«      |j                  |j
                  t        j                  dt         j                  ¬«      f«       Œãt	        |«      dkD  sŒòt	        |«      dk(  r‚|j                  t        j                  d|j                  ft        ¬«      t        j                  dt         j                  ¬«      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«      ‚| j1                  |j
                  �|j
                  nt        j2                  g «      |j
                  �|j
                  nt        j2                  g «      |	|«      }
|j                  |
|j                  |j
                  |j
                  f«       �Œª |sƒt5        | j                  | j6                  t        j                  |j8                  d   «      t        j                  d|j8                  d   f«      |t        j2                  g t        ¬«      ddd¬	«	      S t        |Ž D �cg c]  }t        j:                  |d«      ‘Œ }} | j<                  |Ž \  }}}t5        | j                  | j6                  ||||ddd¬	«	      S c c}w )
a†  Build per-image stats tuples and delegate to class-level computation.

        Each stats tuple is ``(matches, confidence, class_ids, true_class_ids)``:
        - Both empty: skip (no information).
        - Targets empty, predictions present: all predictions are FPs; true_class_ids
          is ``zeros((0,))``.
        - Targets present: IoU matching produces ``matches`` array.
        g      à?gffffffî?é
   r   N©Údtype)r   z-Unsupported metric target for IoU calculation)	r   r   Úprecision_scoresÚprecision_per_classÚiou_thresholdsÚmatched_classesr1   r3   r5   )ÚnpÚlinspaceÚzipÚ_detections_contentr'   Úclass_idÚ
confidenceÚappendÚzerosÚsizeÚbool_Úint32ÚboolÚfloat32Úintr   r   ÚBOXESr   ÚMASKSr   ÚORIENTED_BOUNDING_BOXESr   r(   Ú_match_detection_batchÚarrayÚPrecisionResultr   ÚshapeÚconcatenateÚ_compute_precision_for_classes)r   Úpredictions_listÚtargets_listrD   Ústatsr*   r+   Úprediction_contentsÚtarget_contentsÚiouÚmatchesÚitemsÚconcatenated_statsrB   rC   Úunique_classess                   r   r.   zPrecision._compute›   sQ  € ô Ÿ™ S¨$°Ó3ˆØˆä$'Ð(8¸,Ó$Gó =	Ñ ˆK˜Ø"&×":Ñ":¸;Ó"GÐØ"×6Ñ6°wÓ?ˆOä�7‹|˜qÒ ¤S¨Ó%5¸Ò%9ð ×'Ñ'Ð/°;×3IÑ3IÐ3QØØ—‘äŸ™Ü  Ó-¨~×/BÑ/BÐCÌ2Ï8É8ôð $×.Ñ.Ø#×,Ñ,ÜŸ™ ¬R¯X©XÔ6ðõ	ô �W“ Ó!Ü�{Ó# qÒ(Ø—L‘LäŸH™H a¨×)<Ñ)<Ð%=ÄTÔJÜŸH™H T´·±Ô<ÜŸ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ð —L‘Là#Ø'×2Ñ2Ø'×0Ñ0Ø#×,Ñ,ð	öðm=	ñ~ Ü"Ø"×1Ñ1Ø!%×!6Ñ!6Ü!#§¡¨.×*>Ñ*>¸qÑ*AÓ!BÜ$&§H¡H¨a°×1EÑ1EÀaÑ1HÐ-IÓ$JØ-Ü "§¡¨´3Ô 7Ø"Ø#Ø"ô
ð 
ô EHÈÀKÖP¸5œbŸn™n¨U°AÕ6ÐPÐÐPà/ˆD×/Ñ/Ð1CÐDñ 	>ÐÐ-¨~ô Ø×-Ñ-Ø!×2Ñ2Ø-Ø 3Ø)Ø*ØØØô

ð 
	
ùò Qs   Í N:c                óž  — t        j                  | «      }||   }||   }t        j                  t        j                  ||f«      «      }t        j                  |d¬«      \  }}t        j                  |j
                  d   t        ¬«      }	||	t        j                  ||«      <   | j                  ||||	«      }
| j                  |
«      }| j                  t        j                  k(  rt        j                  |d¬«      }nÊ| j                  t        j                  k(  r#|
j                  d«      }| j                  |«      }nŠ| j                  t        j                   k(  rm|	j#                  t         j$                  «      }	|	j                  «       dk(  r#t        j                  |j
                  d   «      }nt        j&                  |d|	¬«      }||fS )zçCompute precision scores from concatenated stats across all images.

        ``unique_classes`` is the union of GT and predicted classes so that
        predictions of classes absent from GT still count as false positives.
        T)Úreturn_countsr   r@   ©Úaxisé   )rj   Úweights)rF   ÚargsortÚuniquer[   rM   rZ   rS   ÚsearchsortedÚ_compute_confusion_matrixÚ_compute_precisionr   r   ÚMACROÚmeanÚMICROÚsumÚWEIGHTEDÚastyperR   Úaverage)r   rc   Úprediction_confidenceÚprediction_class_idsÚtrue_class_idsÚsorted_indicesrf   Útrue_classesÚtrue_countsÚclass_countsÚconfusion_matrixrC   rB   Úconfusion_matrix_mergeds                 r   r\   z(Precision._compute_precision_for_classes  s   € ô  Ÿ™Ð%:Ð$:Ó;ˆØ˜.Ñ)ˆØ3°NÑCÐô Ÿ™Ü�N‰N˜NÐ,@ÐAÓBó
ˆô %'§I¡I¨nÈDÔ$QÑ!ˆ�kÜ—x‘x × 4Ñ 4°QÑ 7¼sÔCˆØFQˆ”R—_‘_ ^°\ÓBÑCð  ×9Ñ9ØÐ)¨>¸<ó
Ðð
 #×5Ñ5Ð6FÓGÐð × Ñ ¤O×$9Ñ$9Ò9Ü!Ÿw™wÐ':ÀÔCÑØ×"Ñ"¤o×&;Ñ&;Ò;Ø&6×&:Ñ&:¸1Ó&=Ð#Ø#×6Ñ6Ð7NÓOÑØ×"Ñ"¤o×&>Ñ&>Ò>Ø'×.Ñ.¬r¯z©zÓ:ˆLØ×ÑÓ! QÒ&ô $&§8¡8Ð,?×,EÑ,EÀaÑ,HÓ#IÑ ä#%§:¡:Ø'¨a¸ô$Ð ð  Ð!4°nÐDÐDr    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@   rk   ri   é   éÿÿÿÿT)Úreturn_index)rZ   rF   rM   rQ   Ú	enumerateÚwhereÚstackÚhstackrm   rn   rw   rS   )Úpredictions_classesÚtarget_classesrb   rD   Únum_predictionsÚnum_iou_levelsÚcorrectÚcorrect_classÚiÚ	iou_levelÚmatched_indicesÚcombined_indicesÚ
iou_valuesrc   Úresult_corrects                  r   rW   z Precision._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                  ||
«      }nv|
dk(  rAt        j                  |«      }t        j                  ||«      }t        j                  |«      }n0| |	   j                  d«      }d| |	   z
  j                  d«      }|
|z
  }t        j                  |||gd¬«      ||<   Œú |}|S )a3  
        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.

        Returns:
            shape (C, Th, 3), containing the true positives, false
                positives, and false negatives for each class and IoU threshold.
        rk   r   é   r@   ri   )rZ   rF   rM   Úfloat64r†   ru   Úfullrˆ   )Úsorted_matchesÚsorted_prediction_class_idsrf   r   Únum_thresholdsÚnum_classesr€   Ú	class_idxrJ   Úis_classÚnum_truerŒ   Útrue_positivesÚfalse_positivesÚfalse_negativesÚresult_matrixs                   r   rp   z#Precision._compute_confusion_matrix^  sK  € ð8 (×-Ñ-¨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�Ü"$§(¡(¨>Ó":‘à!/°Ñ!9×!=Ñ!=¸aÓ!@�Ø#$ ~°hÑ'?Ñ#?×"DÑ"DÀQÓ"G�Ø"*¨^Ñ";�Ü*,¯(©(Ø °/ÐBÈô+Ð˜YÒ'ð#	ð( 2BˆØÐr    c                óÚ   — | j                   d   dk(  st        d| j                   › �«      ‚| d   }| d   }||z   }t        j                  ||t        j                  |«      |dk7  ¬«      }|}|S )aa  
        Broadcastable function, computing the precision 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 precision for each element.
        r„   r—   z/Confusion matrix must have shape (..., 3), got ).r   ).rk   r   )Úoutr‡   )rZ   r(   rF   ÚdivideÚ
zeros_like)r€   r¡   r¢   ÚdenominatorÚ	precisionÚresult_precisions         r   rq   zPrecision._compute_precision—  sŽ   € ð  ×%Ñ% bÑ)¨QÒ.ÜØAØ#×)Ñ)Ð*ð,óð ð *¨&Ñ1ˆØ*¨6Ñ2ˆà$ Ñ6ˆÜ—I‘IØØÜ—‘˜nÓ-Ø Ñ"ô	
ˆ	ð 5>ÐØÐ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   rT   ÚxyxyrU   ÚmaskÚ_make_empty_contentrV   ÚdataÚgetr	   r'   rF   rX   rR   r(   )r   Ú
detectionsÚresult_boxesÚresult_masksÚobbÚ
result_obbs         r   rI   zPrecision._detections_content¸  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   é   r@   )r   r   r   )r   r¹   rƒ   r­   )
r   r   rT   rF   ÚemptyrR   rU   rQ   rV   r(   )r   Úempty_boxesÚempty_masksÚ	empty_obbs       r   r°   zPrecision._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   Úvaluer®   r¯   rJ   rK   Ú
tracker_idr±   rd   rF   rX   )r   r³   Úsize_categoryÚnew_detectionsÚsizesÚ	size_maskÚkeyrÁ   s           r   Ú_filter_detections_by_sizez$Precision._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.
        )rH   rL   rÈ   )r   r]   r^   rÃ   Únew_predictions_listÚnew_targets_listr*   r+   s           r   r/   z1Precision._filter_predictions_and_targets_by_sizeó  sx   € ð  "ÐØÐÜ$'Ð(8¸,Ó$Gò 	Ñ ˆK˜Ø ×'Ñ'Ø×/Ñ/°¸]ÓKôð ×#Ñ#Ø×/Ñ/°¸ÓGõð		ð $Ð%5Ð5Ð5r    N)r   r   r   r   ©ÚreturnÚNone)r*   úDetections | list[Detections]r+   rÏ   rÍ   r   )rÍ   rY   )r]   úlist[Detections]r^   rÐ   rÍ   rY   )
rc   únpt.NDArray[np.bool_]ry   únpt.NDArray[np.float32]rz   únpt.NDArray[np.int32]r{   rÓ   rÍ   zNtuple[npt.NDArray[np.float64], npt.NDArray[np.float64], npt.NDArray[np.int32]])
rŠ   rÓ   r‹   rÓ   rb   rÒ   rD   rÒ   rÍ   rÑ   )
rš   rÑ   r›   rÓ   rf   rÓ   r   rÓ   rÍ   únpt.NDArray[np.float64])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]])Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rT   r   rv   r   r#   r,   r=   r.   r\   ÚstaticmethodrW   rp   rq   rI   r°   rÈ   r/   © r    r   r   r      sº  „ ñ$ðP '3×&8Ñ&8Ø,;×,DÑ,Dð2à#ð2ð *ó2ó& ðà2ðð /ðð 
ó	ó>ð:i
Ø 0ði
Ø@Pði
à	ói
ðV7Eà&ð7Eð  7ð7Eð 4ð	7Eð
 .ð7Eð
ó7Eðr ðØ2ðà-ðð %ðð 0ð	ð
 
òó ðð< ð6Ø-ð6à%:ð6ð .ð6ð ,ð	6ð
 
!ò6ó ð6ðp ð Ø1ð à	 ò ó ð ó@Jó$JðØ$ðØ5Gðà	óð46à*ð6ð 'ð6ð *ð	6ð
 
3ô6r    r   c                  ó¨   — e Zd ZU dZded<   ded<   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d„Zdd„Z	dd„Z
y)rY   u¶  
    The results of the precision 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.
        averaging_method: the averaging method used to compute the
            precision. Determines how the precision is aggregated across classes.
        precision_at_50: the precision at IoU threshold of `0.5`.
        precision_at_75: the precision at IoU threshold of `0.75`.
        precision_scores: the precision scores at each IoU threshold.
            Shape: `(num_iou_thresholds,)`
        precision_per_class: the precision scores per class and
            IoU threshold. Shape: `(num_classes, num_iou_thresholds)`
        iou_thresholds: the IoU thresholds used in the calculations.
        matched_classes: the class IDs present in either predictions or ground
            truth. Corresponds to the rows of `precision_per_class`. Classes
            that appear only in predictions (no ground-truth instances) are
            included; their per-threshold precision values will be `0.0`.
        small_objects: the Precision metric results
            for small objects (area < 32Â²).
        medium_objects: the Precision metric results
            for medium objects (32Â² â‰¤ area < 96Â²).
        large_objects: the Precision metric results
            for large objects (area â‰¥ 96Â²).
    r   r   r   r   c                ó2   — t        | j                  d   «      S )Nr   ©ÚfloatrB   r"   s    r   Úprecision_at_50zPrecisionResult.precision_at_50*  ó   € ä�T×*Ñ*¨1Ñ-Ó.Ð.r    c                ó2   — t        | j                  d   «      S )Né   rÞ   r"   s    r   Úprecision_at_75zPrecisionResult.precision_at_75.  rá   r    rÔ   rB   rC   rÒ   rD   rÓ   rE   zPrecisionResult | Noner1   r3   r5   c                óú  — | j                   j                  › d| j                  › d| j                  › 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 Precision
            >>> 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])
            ... )
            >>> precision_metric = Precision()
            >>> precision_result = precision_metric.update(
            ...     predictions, targets
            ... ).compute()
            >>> print(precision_result)  # doctest: +ELLIPSIS
            PrecisionResult:
            Metric target:    MetricTarget.BOXES
            Averaging method: AveragingMethod.WEIGHTED
            P @ 50:     1.0000
            P @ 75:     1.0000
            P @ thresh: [1. ... 1.]
            IoU thresh: [0.5  0.55 ... 0.95]
            Precision per class:
              0: [1. ... 1.]
            ...
            Medium objects:
              PrecisionResult:
              Metric target:    MetricTarget.BOXES
              Averaging method: AveragingMethod.WEIGHTED
              P @ 50:     0.0000
              ...

            ```
        z:
Metric target:    z
Averaging method: z
P @ 50:     z.4fz
P @ 75:     z
P @ thresh: z
IoU thresh: z
Precision per class:
r   z  No results
z  z: ú
z
Small objects:
z
Medium objects:
z
Large objects:
)Ú	__class__rÖ   r   r   rà   rä   rB   rD   rC   rN   rH   rE   r1   ÚstrÚreplacer3   r5   )r   Úout_strrJ   Úprecision_of_classÚindentÚindenteds         r   Ú__str__zPrecisionResult.__str__;  sÕ  € ðV �~‰~×&Ñ&Ð'ð (!Ø!%×!3Ñ!3Ð 4ð 5!Ø!%×!6Ñ!6Ð 7ð 8Ø×/Ñ/°Ð4ð 5Ø×/Ñ/°Ð4ð 5Ø×0Ñ0Ð1ð 2Ø×.Ñ.Ð/ð 0%ð&ð 	ð ×#Ñ#×(Ñ(¨AÒ-ØÐ'Ñ'ˆGÜ,/Ø× Ñ  $×":Ñ":ó-
ò 	?Ñ(ˆHÐ(ð ˜˜H˜: RÐ(:Ð';¸2Ð>Ñ>‰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                ó  — t        «        ddl}| 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P@50zP@75Úsmall_objects_Úmedium_objects_Úlarge_objects_)Úindex)
r   Úpandasrà   rä   r1   Ú	to_pandasrd   r3   r5   Ú	DataFrame)r   ÚpdÚpandas_dataÚsmall_objects_dfrÇ   rÁ   Úmedium_objects_dfÚlarge_objects_dfs           r   rõ   zPrecisionResult.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                óö  — ddg}| j                   | j                  g}t        d   gdz  }| j                  �>| j                  }|ddgz  }||j                   |j                  gz  }|t        d   gdz  z  }| j                  �>| j                  }|d	d
gz  }||j                   |j                  gz  }|t        d   gdz  z  }| j
                  �>| j
                  }|ddgz  }||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                  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 precision results.

        ![example_plot](
            https://media.roboflow.com/supervision-docs/metrics/precision_plot_example.png
        ){ align=center width="800" }
        zPrecision@50zPrecision@75r   rƒ   NzSmall: P@50zSmall: P@75r—   zMedium: P@50zMedium: P@75zLarge: P@50zLarge: P@75r¹   Ú	monospacezfont.family)r?   é   )Úfigsizerk   ÚValueÚbold)Ú
fontweightz#Precision, by Object Size
(target: z, averaging: ú)Úcenter)ÚcolorÚaligné-   Úright)ÚrotationÚhag{®Gáz”?z.2fÚbottom)r
  Úvaz
sans-serif)rà   rä   r   r1   r3   r5   ÚpltÚrcParamsÚsubplotsÚset_ylimÚ
set_ylabelr   rÁ   r   Ú	set_titleÚranger'   ÚbarÚ
set_xticksÚset_xticklabelsÚ
get_heightÚtextÚget_xÚ	get_widthÚtight_layoutÚshow)r   ÚlabelsÚvaluesÚcolorsr1   r3   r5   Ú_ÚaxÚtitleÚx_positionsÚbarsr  Úy_values                 r   ÚplotzPrecisionResult.plot¡  sŽ  € ð ! .Ð1ˆØ×&Ñ&¨×(<Ñ(<Ð=ˆÜ& qÑ)Ð*¨QÑ.ˆà×ÑÐ)Ø ×.Ñ.ˆMØ�} mÐ4Ñ4ˆFØ�}×4Ñ4°m×6SÑ6SÐTÑTˆFØÔ+¨AÑ.Ð/°!Ñ3Ñ3ˆFà×ÑÐ*Ø!×0Ñ0ˆNØ�~ ~Ð6Ñ6ˆFØ�~×5Ñ5°~×7UÑ7UÐVÑVˆFØÔ+¨AÑ.Ð/°!Ñ3Ñ3ˆFà×ÑÐ)Ø ×.Ñ.ˆMØ�} mÐ4Ñ4ˆFØ�}×4Ñ4°m×6SÑ6SÐTÑTˆFØÔ+¨AÑ.Ð/°!Ñ3Ñ3ˆFà&1Œ�‰�]Ñ#ä—‘ WÔ-‰ˆˆ2Ø
�‰�A�qÔØ
�‰�g¨&ˆÔ1ðØ×,Ñ,×2Ñ2Ð3ð 4Ø×0Ñ0×6Ñ6Ð7°qð:ð 	ð
 	�‰�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)rÍ   rß   )rÍ   rè   )rÍ   zpd.DataFramerÌ   )rÖ   r×   rØ   rÙ   Ú__annotations__Úpropertyrà   rä   rî   rõ   r&  rÛ   r    r   rY   rY     sx   … ñð:  ÓØ%Ó%àò/ó ð/ð ò/ó ð/ð .Ó-Ø0Ó0Ø+Ó+Ø*Ó*à)Ó)Ø*Ó*Ø)Ó)óFóP4ô<>r    rY   )'Ú
__future__r   Úcopyr   Údataclassesr   Útypingr   r   ÚnumpyrF   Únumpy.typingÚnptÚ
matplotlibr   r  Úsupervision.configr	   Úsupervision.detection.corer
   Ú'supervision.detection.utils.iou_and_nmsr   r   r   Úsupervision.draw.colorr   Úsupervision.metrics.corer   r   r   Ú%supervision.metrics.utils.object_sizer   r   Úsupervision.metrics.utils.utilsr   rô   r÷   r   rY   rÛ   r    r   ú<module>r8     sq   ðÝ "å Ý !ß %ã Ý Ý $å 7Ý 1÷ñ õ
 8ß JÑ J÷õ DáÛôg6�ô g6ðT ÷Vð Vó ñVr    