§
    ­¸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	m
Z
 ddlmZ ddlmZ dd	lmZ  e¦   «         Z ed
d
¬¦  «         G d„ d¦  «        ¦   «         Z	 	 	 ddd„ZdS )a¦  Detection decoding shared by the export inference helpers.

Turning an exported model's raw ``dets``/``labels`` tensors into pixel-space detections is identical for every format:
per-class sigmoid, drop the background slot, rank query/class pairs globally, threshold, then convert normalised
``cxcywh`` to pixel ``xyxy``. Matching the raw tensors to their roles is *not* shared -- ONNX keeps its output names
while ``onnx2tf`` usually strips them -- so each format module does its own matching and calls :func:`decode_detections`
with the result.

This decode mirrors ``PostProcess.forward`` in ``rfdetr/models/postprocess.py``; the parity suite depends on it staying
that way.
é    )Úannotations)Ú	dataclass)ÚAnyN)ÚNDArray)Ú_exclude_background_class)Ú_select_topk_multiclass)Ú
get_loggerT)ÚfrozenÚslotsc                  ó<   — e Zd ZU dZded<   ded<   ded<   ded<   d	S )
ÚDecodedDetectionsa>  One image's decoded detections, ordered by descending confidence.

    Attributes are separate arrays rather than a :class:`supervision.Detections` so that a caller with an extra per-
    detection output -- segmentation masks, keypoints -- can gather it with *query_index* before assembling the final
    object.
    zNDArray[np.float32]ÚxyxyúNDArray[np.floating[Any]]Ú
confidencezNDArray[np.int64]Úclass_idÚquery_indexN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__© ó    úm/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/rfdetr/export/_runtime/decode.pyr   r   !   sP   € € € € € € ðð ð ÐÐÑà)Ð)Ð)Ñ)àÐÐÑð #Ð"Ð"Ñ"Ð"Ð"r   r   ç333333Ó?éÿÿÿÿÚ	boxes_cwhr   ÚlogitsÚ
image_sizeútuple[int, int]Ú	thresholdÚfloatÚ
num_selectú
int | NoneÚbackground_class_idÚreturnc           
     óü  — |j         r�t                               d|j        t	          |                     ¦   «         ¦  «        t	          |                     ¦   «         ¦  «        t	          |                     ¦   «         ¦  «        ¦  «         n t                               d|j        ¦  «         t          j	        d|j
        ¬¦  «        }||t          j        |                     dd¦  «         ¦  «        z   z  }t          ||¦  «        \  }}|€|j        d         n|}	t          |||	¬	¦  «        \  }
}}||         }|j         rut                               d
t	          |                     ¦   «         ¦  «        t	          |                     ¦   «         ¦  «        |t          |
j        d         ¦  «        ¦  «         n4t                               d|t          |
j        d         ¦  «        ¦  «         | |         j        \  }}}}|\  }}t          j        ||||gt          j        ¬¦  «        }t          j        ||dz  z
  ||dz  z
  ||dz  z   ||dz  z   gd¬¦  «        }t          j        ||z  d|¦  «        }t)          ||
||¬¦  «        S )a#  Decode one image's raw model outputs into pixel-space detections.

    RF-DETR uses independent per-class sigmoids, not a mutually exclusive softmax, so the ``(Q, C)`` score grid is
    flattened to ``Q * C`` query/class pairs and the top-scoring pairs are taken *before* thresholding -- mirroring
    ``PostProcess._select_topk``. A per-query ``argmax`` would silently drop every extra class a query scores on.

    Args:
        boxes_cwh: Normalised ``cxcywh`` boxes for one image, shape ``(Q, 4)``.
        logits: Raw class logits for the same image, shape ``(Q, C)``.
        image_size: ``(width, height)`` of the source image at its original resolution, used to scale the normalised
            boxes back to pixels.
        threshold: Confidence threshold; detections at or below this score are dropped.
        num_select: Maximum query/class pairs selected before thresholding. ``None`` uses the exported model's query
            count, matching shipped RF-DETR configurations; pass an explicit value for custom exports.
        background_class_id: Exported class slot to exclude before selection. The default ``-1`` preserves the common
            final-slot background convention. Pass ``None`` for sparse COCO checkpoints, whose final slot is class 90,
            or ``0`` for legacy background-first keypoint checkpoints.

    Returns:
        The decoded detections, ordered by descending confidence.

    Examples:
        >>> import numpy as np
        >>> boxes = np.array([[0.5, 0.5, 1.0, 1.0]], dtype=np.float32)
        >>> logits = np.array([[9.0, -9.0]], dtype=np.float32)
        >>> decoded = decode_detections(boxes, logits, (100, 50), background_class_id=None)
        >>> decoded.xyxy
        array([[  0.,   0., 100.,  50.]], dtype=float32)
        >>> decoded.class_id
        array([0])
    z2Logits stats: shape=%s min=%.3f max=%.3f mean=%.3fzLogits stats: empty shape=%sé   )Údtypei¨ÿÿÿéX   Nr   )r#   uG   Scores stats: min=%.3f max=%.3f â€” detections above threshold %.2f: %du;   Scores stats: empty â€” detections above threshold %.2f: %dé   )Úaxisg        )r   r   r   r   )ÚsizeÚloggerÚdebugÚshaper"   ÚminÚmaxÚmeanÚnpÚasarrayr)   ÚexpÚclipr   r   ÚintÚTÚarrayÚfloat32Ústackr   )r   r   r   r!   r#   r%   ÚoneÚ
scores_allÚ	class_idsÚselection_capÚscoresÚclsÚ	query_idxÚcxÚcyÚbwÚbhÚwidthÚheightÚscaler   s                        r   Údecode_detectionsrK   5   sP  € ðP „{ð 	CÝ�ŠØ@ØŒLÝ�&—*’*‘,”,ÑÔÝ�&—*’*‘,”,ÑÔÝ�&—+’+‘-”-Ñ Ô ñ	
ô 	
ð 	
ð 	
õ 	�ŠÐ3°V´\ÑBÔBÐBÝ
Œ*�Q˜fœlÐ
+Ñ
+Ô
+€CØ˜�bœf f§k¢k°#°rÑ&:Ô&:Ð%:Ñ;Ô;Ñ;Ñ<€JÝ5°jÐBUÑVÔVÑ€J�	à'1Ð'9�F”L ”O�O¸z€MÝ4°ZÀÐWdÐeÑeÔeÑ€FˆC�Ø
�CŒ.€CØ„ð 	uÝ�ŠØUÝ�*—.’.Ñ"Ô"Ñ#Ô#Ý�*—.’.Ñ"Ô"Ñ#Ô#ØÝ�”˜Q”Ñ Ô ñ	
ô 	
ð 	
ð 	
õ 	�ŠÐRÐT]Õ_bÐciÔcoÐpqÔcrÑ_sÔ_sÑtÔtÐtà˜yÔ)Ô+�N€BˆˆB�Ø�M€Eˆ6ÝŒH�e˜V U¨FÐ3½2¼:ÐFÑFÔF€EÝŒ8�R˜"˜q™&‘[ " r¨A¡v¡+¨r°B¸±F©{¸BÀÀaÁ¹KÐHÈqÐQÑQÔQ€DÝŒ7�4˜%‘<  eÑ,Ô,€DÝ $°6ÀCÐU^Ð_Ñ_Ô_Ð_r   )r   Nr   )r   r   r   r   r   r    r!   r"   r#   r$   r%   r$   r&   r   )r   Ú
__future__r   Údataclassesr   Útypingr   Únumpyr4   Únumpy.typingr   Úrfdetr.export._class_layoutr   Úrfdetr.export._topkr   Úrfdetr.utilities.loggerr	   r.   r   rK   r   r   r   ú<module>rT      s&  ðð
ð 
ð #Ð "Ð "Ð "Ð "Ð "à !Ð !Ð !Ð !Ð !Ð !Ø Ð Ð Ð Ð Ð à Ð Ð Ð Ø  Ð  Ð  Ð  Ð  Ð  à AÐ AÐ AÐ AÐ AÐ AØ 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø .Ð .Ð .Ð .Ð .Ð .à	ˆ‰Œ€ð €�$˜dÐ#Ñ#Ô#ð#ð #ð #ð #ð #ñ #ô #ñ $Ô#ð#ð. Ø!Ø&(ðI`ð I`ð I`ð I`ð I`ð I`ð I`r   