
    ^jR                     d    d Z ddlZddlmc mZ ddlmZ ddlmZ  G d dej                        Z	y)zGPost-processing module for converting model outputs to COCO API format.    N)nn)box_opsc                       e Zd ZdZ	 	 	 d,dedee   dz  deddf fdZ ej                         de
eej                  f   d	ej                  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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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d*       Zedej                  dej                  dej                  dee
eej                  f      fd+       Z xZS )-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
num_selectnum_keypoints_per_classtrace_alphareturnc                 T    t         |           || _        |xs g | _        || _        y )N)super__init__r   r   r	   )selfr   r   r	   	__class__s       d/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/rfdetr/models/postprocess.pyr   zPostProcess.__init__   s,     	$'>'D"$&    outputstarget_sizesc                 \   |d   |d   }}|j                  dd      }|j                  dd      }| j                  ||||       | j                  |      \  }}}	| j                  ||	|      }
|| j	                  ||||
|	|      S || j                  ||||
|	|      S | j                  |||
      S )a5  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.

        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``.
        pred_logits
pred_boxes
pred_masksNpred_keypoints)get_validate_outputs_select_topk_gather_and_scale_boxes_postprocess_masks_postprocess_keypoints_postprocess_boxes)r   r   r   
out_logitsout_bbox	out_masksout_keypointsscoreslabels
topk_boxesboxess              r   forwardzPostProcess.forward&   s      '}5w|7LH
KKd3	$4d;z9m\R%)%6%6z%B"
,,Xz<P **9ffeZYeff$..}ffeU_amnn&&vvu==r   r    r"   r#   c                 |    ||t        d      t        |       t        |      k(  sJ |j                  d   dk(  sJ y)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.      )
ValueErrorlenshape)r    r"   r#   r   s       r   r   zPostProcess._validate_outputsC   sK    ,  ]%>]^^:#l"3333!!!$)))r   c                 2   |j                         }|j                  |j                  d   d      }t        | j                  |j                  d         }t        j                  ||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   r*   dimr+   )sigmoidviewr.   minr   torchtopk)
r   r    problogits_for_topknum_to_selecttopk_valuestopk_indexesr$   r&   r%   s
             r   r   zPostProcess._select_topk^   s     !!#))J$4$4Q$7<DOO_-B-B1-EF$)JJST$U!\!Z%5%5a%88

 0 0 33vz))r   r!   r&   c           	         t        j                  |       }t        j                  |d|j	                  d      j                  ddd            }|j                  d      \  }}t        j                  ||||gd      j                  |j                        }||dddddf   z  }|j                  d      j                  |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.
        r*   r0      r1   N        )max)r   box_cxcywh_to_xyxyr6   gather	unsqueezerepeatunbindstacktodtype	clamp_minclamp)r!   r&   r   r'   img_himg_w	scale_fcts          r   r   z#PostProcess._gather_and_scale_boxess   s    " **84UAz';';B'?'F'Fq!Q'OP#**1-uKKue <!DGGT		!T1*--$**yD!/D*Er   r$   r%   r'   c                    g }t        | j                  d         D ]  }||   ||   ||   d}||   }	t        j                  | |   d|	j	                  d      j	                  d      j                  d| j                  d   | j                  d               }
||   j                         \  }}t        j                  |
j	                  d      t        |      t        |      fdd      }
|
d	kD  |d
<   |j                  |        |S )a  Attach resized 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.

        Returns:
            One result dict per image containing scores, labels, boxes, and
            boolean masks resized to the target image size.
        r   r$   r%   r'   r0   r*   bilinearF)sizemodealign_cornersr?   masks)ranger.   r6   rB   rC   rD   tolistFinterpolateintappend)r"   r$   r%   r'   r&   r   resultsires_ik_idxmasks_ihws                r   r   zPostProcess._postprocess_masks   s   0 yq)* 	"A%ayF1IaQEqMEll!#--b188IOOB<OQZQ`Q`acQdeG
  ?))+DAqmm!!!$CFCF+;*\aG %s]E'NNN5!	" r   c                    g }t        | j                  d      }t        | j                        }	t        |j                  d         D ]  }
||
   }||
   }||
   }| j                  ||
   ||
         }| j                  ||      \  }}|	dkD  r%|dkD  r | j                  |||||
   |||	|      \  }}}|j                  |||||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 multiplied by an uncertainty penalty derived from the
            active keypoints of the predicted class.
        r   )default)keypoints_ilabels_iscores_itarget_sizeoutput_keypointsoutput_keypoint_precisionnum_keypoint_classesmax_num_keypoints)r$   r%   r'   	keypointskeypoint_precision_cholesky)	r@   r   r-   rV   r.   _gather_keypoints_for_queries_empty_keypoint_outputs_decode_keypoints_for_imager[   )r   r#   r$   r%   r'   r&   r   r\   rl   rk   r]   rf   boxes_irg   re   ri   rj   s                    r   r   z"PostProcess._postprocess_keypoints   s   8  < <aH"4#?#?@}**1-. 	AayHAhGayH<<]1=MzZ[}]K:>:V:V!;77 $a',=,AHLHhHh +%% ,Q%5.G)=&7 Ii 	IE*,E NN&&$!13L+	< r   out_keypoints_iquery_indicesc           
          t        j                  | d|j                  d      j                  d      j                  d| j                  d   | j                  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   r0   r*   rP   )r6   rB   rC   rD   r.   )rs   rt   s     r   ro   z)PostProcess._gather_keypoints_for_queries   s\     ||##B'11"5<<Q@U@UVX@Y[j[p[pqs[tu
 	
r   re   rl   c                     | j                  | j                  d   |df      }| j                  | 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_zerosr.   new_fullfloat)re   rl   ri   rj   s       r   rp   z#PostProcess._empty_keypoint_outputs  sc    " '00+2C2CA2FHY[\1]^$/$8$8+:K:KA:NPacd9eglmrgs$t!!:::r   rf   rg   rh   ri   rj   rk   c          	         |j                   d   }	|	||z  k7  rt        d|	 d| d| d      |j                  |j                   d   |||j                   d         }
||k  }|j                         s|||fS |j	                  d	      d   }||   }|
||f   }| j
                  dkD  r&|j                   d   d
k\  r| j                  ||||      }|\  }}|j                   d   d
k\  }t        |      D ]  }||k(  }|j                         s| j                  |   }|dk  r.||   }||d|f   }|d   |z  ||d|df<   |d   |z  ||d|df<   |d   j                         ||d|df<   |sz|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``.
        r*   z#keypoints_i padded slot dimension (z#) must equal num_keypoint_classes (z) * max_num_keypoints (z).r   r0   T)as_tuple   N).r   ).r*   .r+   r+   .r>   )
r.   r,   r4   anynonzeror	   _apply_keypoint_trace_fusionrV   r   r3   )r   re   rf   rg   rh   ri   rj   rk   rl   total_padded_keypoint_slotsreshapedvalid_class_maskvalid_indicesselected_labelsselected_keypointsrK   rL   has_precision	class_idx
class_masknum_active_keypointsout_idxactive_keypointss                          r   rq   z'PostProcess._decode_keypoints_for_image  s[   B '2&7&7&:#&*>AR*RR56Q5R S))=(>>UVgUhhjl  ##a "68I;K\K\]_K`
 $&::##%-/HHH(00$0?B"=1%m_&DEa$6$<$<R$@A$E88=RacuvH"u*0049 34 	gI(I5J>>##'#?#?	#J #q(#J/G1*>S?S>S2STBRSYBZ]bBbW&;';&;Q>?BRSYBZ]bBbW&;';&;Q>?BRSYBZBbBbBdW&;';&;Q>?L\]`bcdebe]eLf)'3H4H3H*HI	g  )+DDDr   r   r   r   c                    t        | j                        }|j                  |j                  d         }t	        |      D ]J  }||k(  }|j                         s| j                  |   }	|	dk  r.||d|	f   }
| j                  |
      ||<   L |j                         }||   t        j                  | j                   |z        z  ||<   |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)``. The trace is the
            findability-weighted mean expected squared localization error
            implied by the predicted precision-Cholesky parameters.
        r   N)r-   r   ry   r.   rV   r   _keypoint_log_mean_tracecloner6   expr	   )r   rg   r   r   r   rk   log_mean_tracesr   r   r   r   s              r   r   z(PostProcess._apply_keypoint_trace_fusiong  s    0  #4#?#?@,667L7LQ7OP 34 	ZI(I5J>>##'#?#?	#J #q( 1*>S?S>S2ST*.*G*GHX*YOJ'	Z >>#"*="9EIItGWGWFWZiFi<j"jr   r   c                    | d   }| d   }| d   }| d   j                         }d|z  }d|z  }dt        j                  |j                         j	                  d            z  |z   |z   }t        j
                  t        j                  |||gd	
      d	
      }t        j                  |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.
        ).r>   ).   ).   r   g       g       @g-q=)r5   r0   r1   )r3   r6   logabsrJ   	logsumexprF   )
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uyyU!;<<vEN//%++vvv6NTV*W]_`YYv|||67
;DuWagiGjjjr   c           	      ^    t        | ||      D cg c]  \  }}}|||d c}}}S c c}}}w )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.
        rO   )zip)r$   r%   r'   scorelabelboxs         r   r   zPostProcess._postprocess_boxes  s8      [^^dflnsZtuuEVUESV5EC@uuus   ()i,  Ng?)__name__
__module____qualname____doc__rZ   listr{   r   r6   no_graddictstrTensorr(   staticmethodr   tupler   r   r   r   ro   rp   rq   r   r   r   __classcell__)r   s   @r   r   r      sh    48 		'	' "&cT!1	' 		'
 
	' U]]_>tC$56 >ell >W[\`adfkfrfrar\sWt > >8 *LL*<<$&* ||d** ll	*
 
* *4*u|| *ellELLZ_ZfZf>f8g ** ,,LL ll 
	 2 &<<&& & ||	&
 LL& ll& 
d3$%	&& &P=||= = 	=
 ||= LL= ll= 
d3$%	&=~ 
u|| 
TYT`T` 
ejeqeq 
 
" ;\\;; 
u||U\\)	*; ;(IE \\IE ,,	IE
 ,,IE \\IE  ,,IE $)<<IE "IE IE 
u||U\\5<<7	8IEV.,,. ||. 	.
 "LL. 
.` k5<< kELL k k< vvv ||v 
d3$%	&	v vr   r   )
r   r6   torch.nn.functionalr   
functionalrX   rfdetr.utilitiesr   Moduler    r   r   <module>r      s.    N     $sv")) svr   