§
    ­¸jƒ)  ã                  ó’   — d Z ddlmZ ddlmZ ddlmZ ddlZddl	Z	ddl
mZ  G d„ dee¦  «        Zdd„ZdZdZ G d„ d¦  «        ZdS )zVOKS keypoint mAP metric backed by :class:`~rfdetr.evaluation.coco_eval.CocoEvaluator`.é    )Úannotations)ÚEnum)ÚAnyN)ÚCocoEvaluatorc                  ó"   — e Zd ZdZdZdZdZdZdS )ÚOKSKeyuf  Keys returned by :meth:`MetricKeypointOKS.compute`.

    Subclasses :class:`str` so enum members compare equal to their string values
    and can be used interchangeably as dict keys â€” ``stats[OKSKey.MAP]`` and
    ``stats["map"]`` both work.

    Examples:
        >>> OKSKey.MAP == "map"
        True
        >>> OKSKey.MAP_50.value
        'map_50'
    ÚmapÚmap_50Úmap_75ÚmarN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚMAPÚMAP_50ÚMAP_75ÚMAR© ó    ún/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/evaluation/keypoint_oks.pyr   r      s.   € € € € € ðð ð €CØ€FØ€FØ
€C€C€Cr   r   Úpredictionsúdict[int, dict[str, Any]]Úreturnc                ó>   — d„ |                       ¦   «         D ¦   «         S )a  Return a copy of *predictions* with all tensors detached and moved to CPU.

    Prevents callers from inadvertently retaining CUDA memory or autograd graphs
    between :meth:`MetricKeypointOKS.update` calls.  Non-tensor values are kept as-is.

    Args:
        predictions: Per-image prediction dict mapping ``image_id`` to a dict of
            tensor-valued fields (``boxes``, ``scores``, ``labels``, ``keypoints``).

    Returns:
        New dict with the same structure; every :class:`torch.Tensor` value is
        replaced by its ``.detach().cpu()`` copy.

    Examples:
        >>> import torch
        >>> preds = {1: {"scores": torch.tensor([0.9], device="cpu"), "label": 2}}
        >>> sanitized = _sanitize_preds(preds)
        >>> sanitized[1]["label"]
        2
    c                óR   — i | ]$\  }}|d „ |                      ¦   «         D ¦   «         “Œ%S )c                óš   — i | ]H\  }}|t          |t          j        ¦  «        r&|                     ¦   «                              ¦   «         n|“ŒIS r   )Ú
isinstanceÚtorchÚTensorÚdetachÚcpu)Ú.0ÚkeyÚvalues      r   ú
<dictcomp>z._sanitize_preds.<locals>.<dictcomp>.<dictcomp>=   sW   € ð 
ð 
ð 
ÙXbÐX[Ð]bˆC­°E½5¼<Ñ)HÔ)HÐS�—’‘”×#Ò#Ñ%Ô%Ð%Èeð
ð 
ð 
r   ©Úitems)r#   Úimage_idÚpredss      r   r&   z#_sanitize_preds.<locals>.<dictcomp><   sV   € ð ð ð ñ ˆH�eð 	ð 
ð 
Øfk×fqÒfqÑfsÔfsð
ñ 
ô 
ðð ð r   r'   )r   s    r   Ú_sanitize_predsr+   '   s1   € ð*ð ð  +×0Ò0Ñ2Ô2ð	ñ ô ð r   iô  )é
   c                  óP   — e Zd ZdZdefdd„Zedd„¦   «         Zdd„Zdd„Z	dd„Z
dS )ÚMetricKeypointOKSuÌ  OKS keypoint mAP metric backed by CocoEvaluator.

    Plain Python facade over :class:`~rfdetr.evaluation.coco_eval.CocoEvaluator`
    with a :meth:`reset` / :meth:`update` / :meth:`compute` interface that mirrors
    the torchmetrics API shape without subclassing it.

    DDP synchronisation is handled inside :meth:`compute` via
    :meth:`~rfdetr.evaluation.coco_eval.CocoEvaluator.synchronize_between_processes`,
    which uses the repo's pickle-based ``all_gather`` â€” avoiding the torchmetrics
    deadlock bugs #931 / #449 that affect variable-shape state tensors.

    Supports arbitrary keypoint counts and per-category OKS sigmas through the
    underlying :class:`~rfdetr.evaluation.coco_eval._GroupedKeypointCOCOeval`.

    When TorchMetrics ships production-quality arbitrary-keypoint support (tracked
    in upstream PR #3348), the internals of :meth:`compute` can delegate to
    ``MeanAveragePrecision(iou_type="keypoints", keypoint_format="xyv")`` without
    any change to callers.  Note: when migrating, ``"mar"`` will need remapping to
    ``"mar_<max_dets>"`` as TorchMetrics uses a suffixed key name.

    Args:
        coco_gt: Ground-truth COCO object.  Accepted types: :class:`faster_coco_eval.COCO`
            or any object with a ``.dataset`` dict and optional ``.label2cat`` mapping
            (the duck-typed surface required by :class:`~rfdetr.evaluation.coco_eval.CocoEvaluator`).
        keypoint_oks_sigmas: Per-keypoint OKS sigmas. When ``None``, falls back to
            COCO person sigmas for 17-keypoint datasets or a uniform 0.05 sigma for
            other counts.
        max_dets: Maximum detections per image passed to the underlying
            :class:`~rfdetr.evaluation.coco_eval.CocoEvaluator`.  Defaults to 500.

            Note:
                For keypoint evaluation the underlying COCO evaluator overrides
                ``maxDets`` to ``[20]`` regardless of this value â€” this parameter
                is forwarded but has no effect on keypoint evaluation.

    Examples:
        >>> from unittest.mock import MagicMock
        >>> metric = MetricKeypointOKS(MagicMock(), max_dets=100)
        >>> metric.has_updates
        False
        >>> metric.reset()  # idempotent on empty state
    NÚcoco_gtr   Úkeypoint_oks_sigmasúlist[float] | NoneÚmax_detsÚintr   ÚNonec                ó>   — || _         || _        || _        g | _        d S )N)Ú_coco_gtÚ_keypoint_oks_sigmasÚ	_max_detsÚ_batches)Úselfr/   r0   r2   s       r   Ú__init__zMetricKeypointOKS.__init__}   s'   € ð  ˆŒØ$7ˆÔ!Ø!ˆŒð :<ˆŒˆˆr   Úboolc                ó*   — t          | j        ¦  «        S )aß  Return whether any predictions have been accumulated since last reset.

        Returns:
            ``True`` if :meth:`update` has been called at least once since the
            last :meth:`reset`.

        Examples:
            >>> from unittest.mock import MagicMock
            >>> metric = MetricKeypointOKS(MagicMock())
            >>> metric.has_updates
            False
            >>> metric.update({1: {}})
            >>> metric.has_updates
            True
        )r<   r9   ©r:   s    r   Úhas_updateszMetricKeypointOKS.has_updates‘   s   € õ" �D”MÑ"Ô"Ð"r   c                ó8   — | j                              ¦   «          dS )a!  Clear accumulated predictions.

        Examples:
            >>> from unittest.mock import MagicMock
            >>> metric = MetricKeypointOKS(MagicMock())
            >>> metric.update({1: {}})
            >>> metric.reset()
            >>> metric.has_updates
            False
        N)r9   Úclearr>   s    r   ÚresetzMetricKeypointOKS.reset¤   s   € ð 	Œ×ÒÑÔÐÐÐr   r   r   c                óT   — | j                              t          |¦  «        ¦  «         dS )u]  Accumulate per-batch predictions.

        Each call appends one batch; predictions are replayed in order inside
        :meth:`compute`.  Predictions for the same ``image_id`` across different
        calls are preserved as separate entries â€” no overwrite.

        Args:
            predictions: Mapping from ``image_id`` to a prediction dict with keys
                ``boxes`` (``[N, 4]`` xyxy pixel coords), ``scores`` (``[N]``),
                ``labels`` (``[N]`` int), and ``keypoints`` (``[N, K, 3]``
                x/y/confidence in pixel coords). Pass an empty dict for images
                with no predictions.

        Examples:
            >>> from unittest.mock import MagicMock
            >>> metric = MetricKeypointOKS(MagicMock())
            >>> metric.update({1: {}, 2: {}})
            >>> metric.has_updates
            True
        N)r9   Úappendr+   )r:   r   s     r   ÚupdatezMetricKeypointOKS.update±   s(   € ð* 	Œ×Ò�_¨[Ñ9Ô9Ñ:Ô:Ð:Ð:Ð:r   údict[str, float]c                óR  — t          | j        dg| j        | j        d¬¦  «        }| j        D ]}|                     |¦  «         Œ|                     ¦   «          |                     ¦   «          |j        d         }|j	        }|j
        t          k    sJ dt          › d|j
        › d�¦   «         ‚t          j        t          |d         ¦  «        t          j        t          |d         ¦  «        t          j        t          |d	         ¦  «        t          j        t          |d
         ¦  «        iS )a  Run OKS keypoint evaluation and return metric dict.

        Constructs a fresh :class:`~rfdetr.evaluation.coco_eval.CocoEvaluator`,
        replays all accumulated per-batch predictions in order (matching the
        original per-batch ``CocoEvaluator.update()`` call pattern), synchronises
        across DDP ranks via
        :meth:`~rfdetr.evaluation.coco_eval.CocoEvaluator.synchronize_between_processes`,
        and accumulates COCO keypoint statistics.

        Returns:
            Dict with float values for keys :attr:`OKSKey.MAP` (mAP@50:95),
            :attr:`OKSKey.MAP_50` (AP@50), :attr:`OKSKey.MAP_75` (AP@75),
            and :attr:`OKSKey.MAR` (AR@50:95).  A value of ``-1.0`` indicates
            the statistic was not available (e.g. no predictions matched any ground-truth
            annotation).  Callers should filter ``value < 0`` before logging.

        Examples:
            >>> from unittest.mock import MagicMock, patch
            >>> import numpy as np
            >>> metric = MetricKeypointOKS(MagicMock(), max_dets=500)
            >>> fake_eval = MagicMock()
            >>> fake_eval.coco_eval = {
            ...     "keypoints": MagicMock(stats=np.array([0.5, 0.7, 0.4, -1, -1, 0.6, -1, -1, -1, -1]))
            ... }
            >>> with patch("rfdetr.evaluation.keypoint_oks.CocoEvaluator", return_value=fake_eval):
            ...     metric.update({1: {}})
            ...     result = metric.compute()
            >>> result["map"]
            0.5
            >>> result["map_50"]
            0.7
        Ú	keypointsF)r2   r0   Úlog_summaryz#Expected coco keypoint stats shape z, got uR   ; pycocotools _summarizeKps() contract violated â€” check faster_coco_eval versionr   é   é   é   )r   r6   r8   r7   r9   rE   Úsynchronize_between_processesÚ
accumulateÚ	coco_evalÚstatsÚshapeÚ_KPS_STATS_SHAPEr   r   Úfloatr   r   r   )r:   Ú	evaluatorÚbatchÚcoco_eval_entryrP   s        r   ÚcomputezMetricKeypointOKS.computeÈ   s+  € õB "ØŒMØˆMØ”^Ø $Ô 9Øð
ñ 
ô 
ˆ	ð ”]ð 	$ð 	$ˆEØ×Ò˜UÑ#Ô#Ð#Ð#Ø×/Ò/Ñ1Ô1Ð1Ø×ÒÑÔÐØ(Ô2°;Ô?ˆØ&5Ô&;ˆØŒ{Õ.Ò.Ð.Ð.ð_Õ2Bð _ð _È%Ì+ð _ð _ð _ñ /Ô.Ð.õ
 ŒJ�˜e Aœh™œÝŒM�5  q¤™?œ?ÝŒM�5  q¤™?œ?ÝŒJ�˜e Aœh™œð	
ð 	
r   )r/   r   r0   r1   r2   r3   r   r4   )r   r<   )r   r4   )r   r   r   r4   )r   rF   )r   r   r   r   ÚDEFAULT_KEYPOINT_MAX_DETSr;   Úpropertyr?   rB   rE   rW   r   r   r   r.   r.   Q   sœ   € € € € € ð)ð )ð\ 37Ø1ð	<ð <ð <ð <ð <ð( ð#ð #ð #ñ „Xð#ð$ð ð ð ð;ð ;ð ;ð ;ð.7
ð 7
ð 7
ð 7
ð 7
ð 7
r   r.   )r   r   r   r   )r   Ú
__future__r   Úenumr   Útypingr   ÚnumpyÚnpr   Úrfdetr.evaluation.coco_evalr   Ústrr   r+   rX   rR   r.   r   r   r   ú<module>ra      sø   ðð ]Ð \à "Ð "Ð "Ð "Ð "Ð "à Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø €€€à 5Ð 5Ð 5Ð 5Ð 5Ð 5ðð ð ð ð ˆS�$ñ ô ð ð(ð ð ð ðD  Ð ð
 Ð ðn
ð n
ð n
ð n
ð n
ñ n
ô n
ð n
ð n
ð n
r   