§
    ­¸jÝn  ã                   óf   — d Z ddlZddlmc mZ ddlmZ ddlmZ dZ G d„ dej	        ¦  «        Z
dS )zGPost-processing module for converting model outputs to COCO API format.é    N)Únn)Úbox_opsé    c                   ó2  ‡ — e Zd ZdZ	 	 	 	 d2dedee         dz  ded	ed
df
ˆ fd„Z e	j
        ¦   «         	 d3deee	j        f         de	j        dedz  d
eeee	j        f                  fd„¦   «         Zede	j        de	j        dz  de	j        dz  de	j        d
df
d„¦   «         Zde	j        d
ee	j        e	j        e	j        f         fd„Zede	j        de	j        de	j        d
e	j        fd„¦   «         Ze	 d4ddœde	j        de	j        de	j        de	j        de	j        de	j        d	ededz  d
eeee	j        f                  fd„¦   «         Zde	j        de	j        de	j        de	j        de	j        de	j        d
eeee	j        f                  fd„Zede	j        de	j        d
e	j        fd „¦   «         Zed!e	j        d"ed
ee	j        e	j        f         fd#„¦   «         Zd!e	j        d$e	j        d%e	j        d&e	j        d'e	j        d(e	j        d)ed"ed
ee	j        e	j        e	j        f         fd*„Zd%e	j        d+e	j        d,e	j        d-e	j        d
e	j        f
d.„Zed/e	j        d
e	j        fd0„¦   «         Zede	j        de	j        de	j        d
eeee	j        f                  fd1„¦   «         Zˆ xZS )5ÚPostProcessab  Convert raw RF-DETR model outputs into per-image prediction tensors.

    The postprocessor is shared by detection, segmentation, and keypoint inference. It selects top scoring query/class
    pairs, scales boxes back to the requested image sizes, and then delegates to the head-specific private helper for
    masks, keypoints, or box-only results.
    é,  Nçš™™™™™É?TÚ
num_selectÚnum_keypoints_per_classÚtrace_alphaÚupsample_masks_to_image_sizeÚreturnc                 ó´   •— t          ¦   «                              ¦   «          |dk     rt          d|› �¦  «        ‚|| _        |pg | _        || _        || _        d S )Nr   z%num_select must be non-negative; got )ÚsuperÚ__init__Ú
ValueErrorr
   r   r   r   )Úselfr
   r   r   r   Ú	__class__s        €úi/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/models/postprocess.pyr   zPostProcess.__init__   se   ø€ õ 	‰Œ×ÒÑÔÐØ˜Š>ˆ>ÝÐQÀZÐQÐQÑRÔRÐRØ$ˆŒØ'>Ð'DÀ"ˆÔ$Ø&ˆÔØ,HˆÔ)Ð)Ð)ó    ÚoutputsÚtarget_sizesÚscore_thresholdc           
      ó´  — |d         |d         }}|                      d¦  «        }|                      d¦  «        }|                      ||||¦  «         |                      |¦  «        \  }}	}
|                      ||
|¦  «        }|�"|                      |||	||
|| j        |¬¦  «        S |�|                      |||	||
|¦  «        S |                      ||	|¦  «        S )uP  Convert raw model tensors into per-image detection dictionaries.

        Args:
            outputs: Model output dictionary containing ``pred_logits`` and ``pred_boxes`` plus optional
                ``pred_masks`` or ``pred_keypoints``.
            target_sizes: Per-image ``(height, width)`` tensor. For inference and evaluation this should be the
                original image size so normalized boxes and keypoints are returned in source-image pixel coordinates.
            score_threshold: Optional confidence threshold already known to the caller. Detections scoring at or
                below it are dropped before masks are resized, so the upsample only runs on detections the caller
                keeps. Only the segmentation path acts on it: the keypoint path rewrites scores after selection
                (uncertainty fusion), so filtering on the pre-fusion scores would not match the caller's own filter,
                and the box-only path has no per-detection work worth skipping. ``None`` (the default) keeps every
                selected detection, which is what evaluation relies on.

        Returns:
            One dictionary per image. Every dictionary contains ``scores``, ``labels``, and ``boxes`` in absolute
            pixel coordinates clamped to the respective image dimensions. Segmentation outputs also contain
            ``masks``. Keypoint outputs also contain ``keypoints`` and ``keypoint_precision_cholesky``. With
            ``score_threshold`` set, segmentation dictionaries hold only the detections above it â€” fewer rows,
            never different ones.
        Úpred_logitsÚ
pred_boxesÚ
pred_masksÚpred_keypointsN©r   )ÚgetÚ_validate_outputsÚ_select_topkÚ_gather_and_scale_boxesÚ_postprocess_masksr   Ú_postprocess_keypointsÚ_postprocess_boxes)r   r   r   r   Ú
out_logitsÚout_bboxÚ	out_masksÚout_keypointsÚscoresÚlabelsÚ
topk_boxesÚboxess               r   ÚforwardzPostProcess.forward.   s  € ð2  ' }Ô5°w¸|Ô7L�Hˆ
Ø—K’K Ñ-Ô-ˆ	ØŸšÐ$4Ñ5Ô5ˆØ×Ò˜z¨9°mÀ\ÑRÔRÐRà%)×%6Ò%6°zÑ%BÔ%BÑ"ˆ�˜
Ø×,Ò,¨X°zÀ<ÑPÔPˆàÐ Ø×*Ò*ØØØØØØØÔ1Ø /ð +ñ 	ô 	ð 	ð Ð$Ø×.Ò.¨}¸fÀfÈeÐU_ÐamÑnÔnÐnØ×&Ò& v¨v°uÑ=Ô=Ð=r   r'   r)   r*   c                 ó–   — |�|�t          d¦  «        ‚t          | ¦  «        t          |¦  «        k    sJ ‚|j        d         dk    sJ ‚dS )aÃ  Validate mutually exclusive output heads and per-image target sizes.

        Args:
            out_logits: Classification logits with shape ``(B, Q, C)``.
            out_masks: Optional mask logits from segmentation models.
            out_keypoints: Optional keypoint predictions from keypoint models.
            target_sizes: Per-image ``(height, width)`` tensor with shape
                ``(B, 2)``.

        Raises:
            ValueError: If both masks and keypoints are present in the model
                outputs at the same time. Mask and keypoint heads are mutually
                exclusive at inference.
            AssertionError: If batch dimensions do not match ``target_sizes``.
        Nz>masks and keypoints cannot be used together in postprocessing.é   é   )r   ÚlenÚshape)r'   r)   r*   r   s       r   r!   zPostProcess._validate_outputs^   s\   € ð, Ð  ]Ð%>ÝÐ]Ñ^Ô^Ð^Ý�:‰Œ¥# lÑ"3Ô"3Ò3Ð3Ð3Ð3ØÔ! !Ô$¨Ò)Ð)Ð)Ð)Ð)Ð)r   c                 ór  — |                      ¦   «         }|                     |j        d         d¦  «        }t          | j        |j        d         ¦  «        }t          j        |ddd¬¦  «        }|dd…d|…f         }|                     d|¦  «        }|}||j        d         z  }	||j        d         z  }
||
|	fS )a²  Select the highest scoring query/class pairs.

        Args:
            out_logits: Classification logits with shape ``(B, Q, C)``.

        Returns:
            Tuple containing selected scores, class labels, and query indices.
            Scores are sigmoid probabilities before any keypoint uncertainty
            fusion. Labels are class indices and query indices select rows from
            box/mask/keypoint outputs.
        r   éÿÿÿÿr1   T)ÚdimÚ
descendingÚstableNr2   )ÚsigmoidÚviewr4   Úminr
   ÚtorchÚargsortÚgather)r   r'   ÚprobÚlogits_for_topkÚnum_to_selectÚsorted_indexesÚtopk_indexesÚtopk_valuesr+   r-   r,   s              r   r"   zPostProcess._select_topky   sÆ   € ð ×!Ò!Ñ#Ô#ˆØŸ)š) JÔ$4°QÔ$7¸Ñ<Ô<ˆÝ˜DœO¨_Ô-BÀ1Ô-EÑFÔFˆõ œ ¸AÈ$ÐW[Ð\Ñ\Ô\ˆØ% a a a¨¨-¨Ð&7Ô8ˆØ%×,Ò,¨Q°Ñ=Ô=ˆØˆØ! ZÔ%5°aÔ%8Ñ8ˆ
Ø 
Ô 0°Ô 3Ñ3ˆØ�v˜zÐ)Ð)r   r(   r-   c           	      óÎ  — t          j        | ¦  «        }t          j        |d|                     d¦  «                             ddd¦  «        ¦  «        }|                     d¦  «        \  }}t          j        ||||gd¬¦  «                             |j	        ¦  «        }||dd…ddd…f         z  }| 
                    d¦  «                             |dd…ddd…f         ¬¦  «        }|S )aë  Gather selected boxes and scale normalized coordinates to pixels.

        Args:
            out_bbox: Normalized ``cxcywh`` boxes with shape ``(B, Q, 4)``.
            topk_boxes: Query indices selected by :meth:`_select_topk`.
            target_sizes: Per-image ``(height, width)`` tensor.

        Returns:
            Absolute ``xyxy`` boxes with shape ``(B, K, 4)`` in pixel units,
            clamped to ``[0, width]`` for x-coordinates and ``[0, height]`` for y-coordinates.
        r1   r6   é   ©r7   Nç        )Úmax)r   Úbox_cxcywh_to_xyxyr=   r?   Ú	unsqueezeÚexpandÚunbindÚstackÚtoÚdtypeÚ	clamp_minÚclamp)r(   r-   r   r.   Úimg_hÚimg_wÚ	scale_fcts          r   r#   z#PostProcess._gather_and_scale_boxes’   sâ   € õ" Ô*¨8Ñ4Ô4ˆÝ”˜U A z×';Ò';¸BÑ'?Ô'?×'FÒ'FÀrÈ2ÈqÑ'QÔ'QÑRÔRˆØ#×*Ò*¨1Ñ-Ô-‰ˆˆuÝ”K ¨¨u°eÐ <À!ÐDÑDÔD×GÒGÈÌÑTÔTˆ	Ø˜	 ! ! ! T¨1¨1¨1 *Ô-Ñ-ˆà—’ Ñ$Ô$×*Ò*¨y¸¸¸¸DÀ!À!À!¸Ô/DÐ*ÑEÔEˆØˆr   r   r+   r,   r.   c          
      óÚ  ‡‡‡— g }|r!| j         d         r|                     ¦   «         ng }	t          | j         d         ¦  «        D �]¤}
||
         ||
         ||
         ||
         f\  }}}}|�@||k                         d¬¦  «        d         }||         ||         }}||         ||         }}|||dœ}| |
                              d|¦  «        Š|s2‰dk                         d¦  «        |d<   |                     |¦  «         Œ¾|	|
         \  ŠŠ‰j        j        d	v o)‰j        j        d
k    o‰j         d         dt          z  k     }‰j         d         dk    rA‰ 
                    ddt          ‰¦  «        t          ‰¦  «        ft          j        ¬¦  «        Š�n7|sFˆˆˆfd„t          d‰j         d         t          ¦  «        D ¦   «         }t          j        |d¬¦  «        Šnï‰ 
                    ‰j         d         dt          ‰¦  «        t          ‰¦  «        ft          j        ¬¦  «        }t          d‰j         d         t          ¦  «        D ]�}t          j        ‰||t          z   …                              d¦  «        t          ‰¦  «        t          ‰¦  «        fdd¬¦  «        }t          j        |d|||t          z   …         ¬¦  «         ~Œ‚|Š‰|d<   |                     |¦  «         �Œ¦|S )uñ  Attach segmentation masks for selected detections.

        Args:
            out_masks: Raw mask logits with shape ``(B, Q, Hm, Wm)``.
            scores: Selected object scores with shape ``(B, K)``.
            labels: Selected class labels with shape ``(B, K)``.
            boxes: Selected absolute boxes with shape ``(B, K, 4)``.
            topk_boxes: Selected query indices with shape ``(B, K)``.
            target_sizes: Per-image ``(height, width)`` tensor used for mask resizing when
                ``upsample_masks_to_image_size`` is ``True``.
            upsample_masks_to_image_size: When ``True`` (default), resize masks to the target
                image size â€” the standard behaviour required for correct-resolution inference
                output. When ``False``, skip the resize and return masks thresholded at the
                model's native ``(Hm, Wm)`` mask-head resolution instead â€” cheaper (no
                interpolation, no chunking needed) but masks are then at a different resolution
                than boxes/ground truth; callers comparing them against full-resolution masks
                (e.g. COCO segm mAP) must downsize the other side to match, or the comparison is
                meaningless. Intended for opt-in, validation-only cost reduction (see
                ``TrainConfig.eval_masks_head_resolution``), not for inference output.
            score_threshold: Optional confidence threshold already known to the caller. Detections scoring at or
                below it are dropped before the gather, so no mask the caller discards is ever gathered, resized or
                thresholded. Applies to both ``upsample_masks_to_image_size`` branches. ``None`` (the default) keeps
                every selected detection.

        Returns:
            One result dict per image containing scores, labels, boxes, and boolean masks â€”
            resized to the target image size, or left at native mask-head resolution per
            ``upsample_masks_to_image_size``.
        r   NT©Úas_tuple©r+   r,   r.   rI   r1   Úmasks>   ÚcpuÚcudar]   rG   )rQ   c           	      óÆ   •— g | ]]}t          j        ‰||t          z   …                              d ¦  «        t	          ‰¦  «        t	          ‰¦  «        fdd¬¦  «        dk    ‘Œ^S )r1   ÚbilinearF©ÚsizeÚmodeÚalign_cornersrI   )ÚFÚinterpolateÚ_MASK_CHUNKrL   Úint)Ú.0ÚstartÚhÚmasks_iÚws     €€€r   ú
<listcomp>z2PostProcess._postprocess_masks.<locals>.<listcomp>ö   s€   ø€ ð 	ð 	ð 	ð õ ”MØ ¨µÑ(;Ð ;Ô<×FÒFÀqÑIÔIÝ! !™fœf¥c¨!¡f¤fÐ-Ø'Ø&+ð	ñ ô ð òð	ð 	ð 	r   rH   r_   Fr`   )Úout)r4   ÚtolistÚrangeÚnonzeroÚindex_selectrL   ÚappendÚdeviceÚtyperf   Ú	new_emptyrg   r=   ÚboolÚcatrd   re   Úgt)r)   r+   r,   r.   r-   r   r   r   ÚresultsÚtarget_sizes_listÚiÚscores_iÚlabels_iÚboxes_iÚk_idxÚselÚres_iÚuse_preallocatedÚchunksÚmasks_resizedri   Úinterpolatedrj   rk   rl   s                         @@@r   r$   zPostProcess._postprocess_masks¬   s-  øøø€ ðR ˆð 6RÐpÐV_ÔVeÐfgÔVhÐp˜L×/Ò/Ñ1Ô1Ð1ÐnpÐÝ�y” qÔ)Ñ*Ô*ð 5	"ñ 5	"ˆAØ17¸´¸FÀ1¼IÀuÈQÄxÐQ[Ð\]ÔQ^Ð1^Ñ.ˆH�h ¨ØÐ*ð   /Ò1×:Ò:ÀDÐ:ÑIÔIÈ!ÔL�Ø%-¨c¤]°H¸S´M˜(�Ø!(¨¤¨u°S¬z˜�Ø'°8ÀgÐNÐNˆEð   ”l×/Ò/°°5Ñ9Ô9ˆGØ/ð Ø")¨C¢-×!:Ò!:¸1Ñ!=Ô!=��g‘Ø—’˜uÑ%Ô%Ð%ØØ$ QÔ'‰DˆAˆqð  'œ~Ô2°oÐEð  Ø”Ô# vÒ-ÐU°'´-ÀÔ2BÀaÍ+ÁoÒ2UðKÐð Œ}˜QÔ 1Ò$Ð$Ø!×+Ò+¨Q°µ3°q±6´6½3¸q¹6¼6Ð,BÍ%Ì*Ð+ÑUÔU�‘Ø%ð (ð	ð 	ð 	ð 	ð 	ð 	õ "' q¨'¬-¸Ô*:½KÑ!HÔ!Hð	ñ 	ô 	�õ  œ) F°Ð2Ñ2Ô2��à '× 1Ò 1°7´=ÀÔ3CÀQÍÈAÉÌÕPSÐTUÑPVÔPVÐ2WÕ_dÔ_iÐ 1Ñ jÔ j�Ý" 1 g¤m°AÔ&6½ÑDÔDð %ð %�EÝ#$¤=Ø ¨µÑ(;Ð ;Ô<×FÒFÀqÑIÔIÝ! !™fœf¥c¨!¡f¤fÐ-Ø'Ø&+ð	$ñ $ô $�Lõ ”H˜\¨3°MÀ%È%ÕR]ÑJ]ÐB]Ô4^Ð_Ñ_Ô_Ð_Ø$˜Ø'�Ø$ˆE�'‰NØ�NŠN˜5Ñ!Ô!Ð!Ñ!Øˆr   c                 óÚ  — g }t          | j        d¬¦  «        }t          | j        ¦  «        }	t          |j        d         ¦  «        D ]£}
||
         }||
         }||
         }|                      ||
         ||
         ¦  «        }|                      ||¦  «        \  }}|	dk    r-|dk    r'|                      |||||
         |||	|¬¦  «        \  }}}|                     |||||dœ¦  «         Œ¤|S )a�  Select class-specific keypoints and optionally fuse object scores.

        Args:
            out_keypoints: Raw keypoint predictions with shape
                ``(B, Q, C * max(K_c), D)`` where keypoint slots are padded per
                class.
            scores: Selected object scores before uncertainty fusion.
            labels: Selected class labels.
            boxes: Selected absolute boxes.
            topk_boxes: Selected query indices.
            target_sizes: Per-image ``(height, width)`` tensor.

        Returns:
            One result dict per image containing postprocessed object scores,
            labels, boxes, pixel-space keypoints, and raw precision-Cholesky
            parameters. When ``trace_alpha > 0``, scores for valid keypoint
            classes are fused with uncertainty from the active keypoints of the
            predicted class and normalized to ``[0, 1)``.
        r   )Údefault)Úkeypoints_ir~   r}   Útarget_sizeÚoutput_keypointsÚoutput_keypoint_precisionÚnum_keypoint_classesÚmax_num_keypoints)r+   r,   r.   Ú	keypointsÚkeypoint_precision_cholesky)	rJ   r   r3   rp   r4   Ú_gather_keypoints_for_queriesÚ_empty_keypoint_outputsÚ_decode_keypoints_for_imagers   )r   r*   r+   r,   r.   r-   r   rz   rŽ   r�   r|   r~   r   r}   r‰   r‹   rŒ   s                    r   r%   z"PostProcess._postprocess_keypoints  sC  € ð8 ˆÝ Ô <ÀaÐHÑHÔHÐÝ" 4Ô#?Ñ@Ô@ÐÝ�}Ô*¨1Ô-Ñ.Ô.ð 	ð 	ˆAØ˜a”yˆHØ˜A”hˆGØ˜a”yˆHØ×<Ò<¸]È1Ô=MÈzÐZ[Ì}Ñ]Ô]ˆKØ:>×:VÒ:VØØ!ñ;ô ;Ñ7ÐÐ7ð $ aÒ'Ð'Ð,=ÀÒ,AÐ,AØHL×HhÒHhØ +Ø%Ø%Ø ,¨Q¤Ø%5Ø.GØ)=Ø&7ð Iiñ 	Iô 	IÑE�Ð*Ð,Eð �NŠNà&Ø&Ø$Ø!1Ø3Lðð ñô ð ð ð ˆr   Úout_keypoints_iÚquery_indicesc                 ó.   — |                       d|¦  «        S )aj  Gather keypoint predictions for the selected query rows of one image.

        Args:
            out_keypoints_i: Keypoint predictions for one image with shape
                ``(Q, C * max(K_c), D)``.
            query_indices: Top-k query indices for that image.

        Returns:
            Keypoint predictions aligned with the selected detections.
        r   )rr   )r”   r•   s     r   r‘   z)PostProcess._gather_keypoints_for_queriesP  s   € ð ×+Ò+¨A¨}Ñ=Ô=Ð=r   r‰   rŽ   c                 ó²   — |                       | j        d         |df¦  «        }|                      | j        d         |dft          d¦  «        ¦  «        }||fS )a  Create zero/NaN-filled keypoint output tensors for one image.

        Args:
            keypoints_i: Gathered selected keypoint predictions for one image.
            max_num_keypoints: Maximum active keypoint count across classes.

        Returns:
            Tuple of pixel-space keypoint output ``(x, y, confidence)`` and raw
            precision-Cholesky output ``(log_l11, l21, log_l22)``. Inactive
            class-padded keypoints remain zeros for coordinates/confidence and
            NaN for precision.
        r   é   Únan)Ú	new_zerosr4   Únew_fullÚfloat)r‰   rŽ   r‹   rŒ   s       r   r’   z#PostProcess._empty_keypoint_outputs`  sf   € ð" '×0Ò0°+Ô2CÀAÔ2FÐHYÐ[\Ð1]Ñ^Ô^ÐØ$/×$8Ò$8¸+Ô:KÈAÔ:NÐPaÐcdÐ9eÕglÐmrÑgsÔgsÑ$tÔ$tÐ!ØÐ!:Ð:Ð:r   r~   r}   rŠ   r‹   rŒ   r�   c          	      ód  — |j         d         }	|	||z  k    rt          d|	› d|› d|› d�¦  «        ‚|                     |j         d         |||j         d         ¦  «        }
||k     }|                     ¦   «         s|||fS |                     d¬	¦  «        d         }||         }|
||f         }| j        dk    r)|j         d         d
k    r|                      ||||¦  «        }|\  }}|j         d         d
k    }t          |¦  «        D ]¨}| j        |         }|dk    rŒ||k    }|dk    r|                     ¦   «         sŒ7||         }||d|…f         }|d         |z  ||d|…df<   |d         |z  ||d|…df<   |d          	                    ¦   «         ||d|…df<   |r|ddd
…f         ||d|…f<   Œ©|||fS )a  Decode selected keypoints for one image into output tensors.

        Args:
            keypoints_i: Gathered selected keypoint predictions for one image.
            labels_i: Predicted class labels for selected detections.
            scores_i: Object scores before optional keypoint uncertainty fusion.
            target_size: Image ``(height, width)`` tensor.
            output_keypoints: Preallocated keypoint output tensor to fill.
            output_keypoint_precision: Preallocated precision output tensor to
                fill.
            num_keypoint_classes: Number of class slots in the keypoint schema.
            max_num_keypoints: Padded keypoint count per class slot.

        Returns:
            Updated object scores, keypoint outputs, and precision outputs. The
            score tensor is cloned only when uncertainty fusion is applied.

        Raises:
            ValueError: If the padded keypoint dimension of ``keypoints_i`` is
                not equal to ``num_keypoint_classes * max_num_keypoints``.
        r1   z#keypoints_i padded slot dimension (z#) must equal num_keypoint_classes (z) * max_num_keypoints (z).r   r6   TrX   é   N).r   ).r1   ©.r2   r2   .rG   )
r4   r   r;   Úanyrq   r   Ú_apply_keypoint_trace_fusionrp   r   r:   )r   r‰   r~   r}   rŠ   r‹   rŒ   r�   rŽ   Útotal_padded_keypoint_slotsÚreshapedÚvalid_class_maskÚvalid_indicesÚselected_labelsÚselected_keypointsrT   rU   Úhas_precisionÚ	class_idxÚnum_active_keypointsÚ
class_maskÚout_idxÚactive_keypointss                          r   r“   z'PostProcess._decode_keypoints_for_imageu  s˜  € ðB '2Ô&7¸Ô&:Ð#Ø&Ð*>ÐARÑ*RÒRÐRÝðlÐ6Qð lð lØ)=ðlð lØVgðlð lð lñô ð ð ×#Ò#ØÔ˜aÔ Ð"6Ð8IÈ;ÔK\Ð]_ÔK`ñ
ô 
ˆð $Ð&:Ò:ÐØ×#Ò#Ñ%Ô%ð 	IØÐ-Ð/HÐHÐHà(×0Ò0¸$Ð0Ñ?Ô?ÀÔBˆØ" =Ô1ˆØ% m°_Ð&DÔEÐØÔ˜aÒÐÐ$6Ô$<¸RÔ$@ÀAÒ$EÐ$EØ×8Ò8¸À=ÐRaÐcuÑvÔvˆHà"‰ˆˆuØ*Ô0°Ô4¸Ò9ˆõ Ð3Ñ4Ô4ð 	gð 	gˆIØ#'Ô#?À	Ô#JÐ Ø# qÒ(Ð(Øà(¨IÒ5ˆJØ# aÒ'Ð'°
·²Ñ0@Ô0@Ð'ØØ# JÔ/ˆGØ1°*Ð>SÐ?SÐ>SÐ2SÔTÐØBRÐSYÔBZÐ]bÑBbÐ˜WÐ&;Ð';Ð&;¸QÐ>Ñ?ØBRÐSYÔBZÐ]bÑBbÐ˜WÐ&;Ð';Ð&;¸QÐ>Ñ?ØBRÐSYÔBZ×BbÒBbÑBdÔBdÐ˜WÐ&;Ð';Ð&;¸QÐ>Ñ?Øð gØL\Ð]`ÐbcÐdeÐbeÐ]eÔLfÐ)¨'Ð3HÐ4HÐ3HÐ*HÑIøàÐ)Ð+DÐDÐDr   r¥   r¦   r§   c                 ó€  — t          | j        ¦  «        }|                     |j        d         ¦  «        }t	          |¦  «        D ][}| j        |         }|dk    rŒ||k    }	|dk    r|	                     ¦   «         sŒ7||	d|…f         }
|                      |
¦  «        ||	<   Œ\|                     ¦   «         }t          j	        ||         ¦  «        | j
        |z  z
  }t          j        |¦  «        }t          j        t          j        |¦  «        t          j        |¦  «        ¦  «        }t          j        ||¦  «        ||<   |S )a?  Fuse object scores with keypoint localization uncertainty.

        Args:
            scores_i: Object scores for one image before keypoint uncertainty
                fusion.
            valid_indices: Detection indices whose predicted class has a
                keypoint schema slot.
            selected_labels: Class labels corresponding to ``valid_indices``.
            selected_keypoints: Class-selected keypoint predictions for those
                detections.

        Returns:
            A score tensor where valid keypoint detections are multiplied by
            ``exp(-trace_alpha * log_mean_trace)`` and then normalized to
            ``[0, 1)``. The trace is the findability-weighted mean expected
            squared localization error implied by the predicted
            precision-Cholesky parameters.
        r   r1   N)r3   r   rš   r4   rp   r    Ú_keypoint_log_mean_traceÚcloner=   Úlogr   r:   Ú	nextafterÚ	ones_likeÚ
zeros_likeÚminimum)r   r}   r¥   r¦   r§   r�   Úlog_mean_tracesr©   rª   r«   r­   Úlog_fused_scoresÚnormalized_scoresÚ	max_scores                 r   r¡   z(PostProcess._apply_keypoint_trace_fusionÄ  sS  € õ2  # 4Ô#?Ñ@Ô@ÐØ,×6Ò6°Ô7LÈQÔ7OÑPÔPˆõ Ð3Ñ4Ô4ð 	Zð 	ZˆIØ#'Ô#?À	Ô#JÐ Ø# qÒ(Ð(ð à(¨IÒ5ˆJØ# aÒ'Ð'°
·²Ñ0@Ô0@Ð'ØØ1°*Ð>SÐ?SÐ>SÐ2SÔTÐØ*.×*GÒ*GÐHXÑ*YÔ*YˆO˜JÑ'Ð'à—>’>Ñ#Ô#ˆÝ œ9 X¨mÔ%<Ñ=Ô=ÀÔ@PÐSbÑ@bÑbÐÝ!œMÐ*:Ñ;Ô;Ðå”OÝŒOÐ-Ñ.Ô.ÝÔÐ.Ñ/Ô/ñ
ô 
ˆ	õ #(¤-Ð0AÀ9Ñ"MÔ"Mˆ�ÑØˆr   r­   c                 ó
  — | d         }| d         }| d         }| d                               ¦   «         }d|z  }d|z  }dt          j        |                     ¦   «                              d¬¦  «        ¦  «        z  |z   |z   }t          j        t          j        |||gd	¬
¦  «        d	¬
¦  «        }t          j        |                     d¬¦  «        ¦  «        }	t          j        ||	z   d	¬
¦  «        t          j        |	d	¬
¦  «        z
  S )aÚ  Compute log mean covariance trace for active keypoints.

        Args:
            active_keypoints: Active keypoint predictions with shape
                ``(..., K, D)`` where ``K`` is the active keypoint count for the
                detection's class and ``D`` is the per-keypoint feature dim.
                Columns ``4:7`` are ``(log_l11, l21, log_l22)`` precision
                Cholesky parameters and column ``2`` is the findable logit. A
                leading batch dimension is supported so this can be called once
                for an entire class group of detections.

        Returns:
            Tensor with the leading batch dimensions of ``active_keypoints``
            (scalar when called on a single detection). Each entry is the log of
            the findability-weighted arithmetic mean trace of the covariance
            matrix. The computation stays in log space for numerical stability
            with very sharp or very uncertain predictions.
        ).rG   ).é   ).é   rŸ   g       Àg       @gê-�™—q=)r<   r6   rH   )r:   r=   r±   ÚabsrS   Ú	logsumexprO   )
r­   Úlog_l11Úl21Úlog_l22Úw_findÚlog_t1Úlog_t2Úlog_t3Úlog_trace_sigmaÚ
log_w_finds
             r   r¯   z$PostProcess._keypoint_log_mean_traceþ  s÷   € ð( # 6Ô*ˆØ˜vÔ&ˆØ" 6Ô*ˆØ! &Ô)×1Ò1Ñ3Ô3ˆØ˜‘ˆØ˜‘ˆØ•u”y §¢¡¤§¢°U Ñ!;Ô!;Ñ<Ô<Ñ<¸vÑEÈÑNˆÝœ/­%¬+°v¸vÀvÐ6NÐTVÐ*WÑ*WÔ*WÐ]_Ð`Ñ`Ô`ˆÝ”Y˜vŸ|š|°˜|Ñ6Ô6Ñ7Ô7ˆ
ÝŒ˜°Ñ;ÀÐDÑDÔDÅuÄÐWaÐgiÐGjÑGjÔGjÑjÐjr   c                 ó8   — d„ t          | ||¦  «        D ¦   «         S )ag  Build detection-only result dictionaries.

        Args:
            scores: Selected object scores with shape ``(B, K)``.
            labels: Selected class labels with shape ``(B, K)``.
            boxes: Selected absolute boxes with shape ``(B, K, 4)``.

        Returns:
            One result dict per image containing scores, labels, and boxes.
        c                 ó"   — g | ]\  }}}|||d œ‘ŒS )rZ   © )rh   ÚscoreÚlabelÚboxs       r   rm   z2PostProcess._postprocess_boxes.<locals>.<listcomp>-  s*   € ÐuÐuÐuÑEVÀUÈEÐSV˜5¨E¸CÐ@Ð@ÐuÐuÐur   )ÚziprZ   s      r   r&   zPostProcess._postprocess_boxes  s)   € ð  vÐuÕZ]Ð^dÐflÐnsÑZtÔZtÐuÑuÔuÐur   )r   Nr	   T)N)T)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rg   Úlistrœ   rw   r   r=   Úno_gradÚdictÚstrÚTensorr/   Ústaticmethodr!   Útupler"   r#   r$   r%   r‘   r’   r“   r¡   r¯   r&   Ú__classcell__)r   s   @r   r   r      sN  ø€ € € € € ðð ð Ø48Ø Ø-1ðIð IàðIð "& c¤¨TÑ!1ðIð ð	Ið
 '+ðIð 
ðIð Ið Ið Ið Ið Ið €U„]�_„_àlpð->ð ->Ø˜C ¤Ð-Ô.ð->Ø>C¼lð->Ø]bÐeiÑ]ið->à	ˆd�3˜œÐ$Ô%Ô	&ð->ð ->ð ->ñ „_ð->ð^ ð*Ø”Lð*à”< $Ñ&ð*ð ”| dÑ*ð*ð ”lð	*ð
 
ð*ð *ð *ñ „\ð*ð4* u¤|ð *¸¸e¼lÈEÌLÐZ_ÔZfÐ>fÔ8gð *ð *ð *ð *ð2 ðØ”,ðà”Lðð ”lðð 
Œð	ð ð ñ „\ðð2 ð .2ðbð )-ðbð bð bØ”<ðbà”ðbð ”ðbð Œ|ð	bð
 ”Lðbð ”lðbð '+ðbð  ™ðbð 
ˆd�3˜œÐ$Ô%Ô	&ðbð bð bñ „\ðbðH=à”|ð=ð ”ð=ð ”ð	=ð
 Œ|ð=ð ”Lð=ð ”lð=ð 
ˆd�3˜œÐ$Ô%Ô	&ð=ð =ð =ð =ð~ ð>°u´|ð >ÐTYÔT`ð >ÐejÔeqð >ð >ð >ñ „\ð>ð ð;Ø”\ð;àð;ð 
ˆuŒ|˜Uœ\Ð)Ô	*ð;ð ;ð ;ñ „\ð;ð(MEð ”\ðMEð ”,ð	MEð
 ”,ðMEð ”\ðMEð  œ,ðMEð $)¤<ðMEð "ðMEð ðMEð 
ˆuŒ|˜Uœ\¨5¬<Ð7Ô	8ðMEð MEð MEð MEð^8à”,ð8ð ”|ð8ð œð	8ð
 "œLð8ð 
Œð8ð 8ð 8ð 8ðt ðk°5´<ð kÀEÄLð kð kð kñ „\ðkð< ðvØ”ðvà”ðvð Œ|ðvð 
ˆd�3˜œÐ$Ô%Ô	&ð	vð vð vñ „\ðvð vð vð vð vr   r   )rÒ   r=   Útorch.nn.functionalr   Ú
functionalrd   Úrfdetr.utilitiesr   rf   ÚModuler   rÊ   r   r   ú<module>rß      s§   ðð NÐ Mà €€€Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð à $Ð $Ð $Ð $Ð $Ð $ð €ðVvð Vvð Vvð Vvð Vv�"”)ñ Vvô Vvð Vvð Vvð Vvr   