§
    ezniã3  ã                   óŠ   — d dl Z d dlmZ d dlmc mZ d dlmZ d dlm	Z	 d dl
mZmZ  G d„ dej        ¦  «        Z	 	 	 	 dd„ZdS )é    N©Úlinear_sum_assignment)Úbbox_iou)Ú	xywh2xyxyÚ	xyxy2xywhc                   ó,   ‡ — e Zd ZdZd
ˆ fd„	Zdd	„Zˆ xZS )ÚHungarianMatcheraÂ  
    A module implementing the HungarianMatcher, which is a differentiable module to solve the assignment problem in an
    end-to-end fashion.

    HungarianMatcher performs optimal assignment over the predicted and ground truth bounding boxes using a cost
    function that considers classification scores, bounding box coordinates, and optionally, mask predictions.

    Attributes:
        cost_gain (dict): Dictionary of cost coefficients: 'class', 'bbox', 'giou', 'mask', and 'dice'.
        use_fl (bool): Indicates whether to use Focal Loss for the classification cost calculation.
        with_mask (bool): Indicates whether the model makes mask predictions.
        num_sample_points (int): The number of sample points used in mask cost calculation.
        alpha (float): The alpha factor in Focal Loss calculation.
        gamma (float): The gamma factor in Focal Loss calculation.

    Methods:
        forward(pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None): Computes the
            assignment between predictions and ground truths for a batch.
        _cost_mask(bs, num_gts, masks=None, gt_mask=None): Computes the mask cost and dice cost if masks are predicted.
    NTFé 1  ç      Ð?ç       @c                 ó°   •— t          ¦   «                              ¦   «          |€ddddddœ}|| _        || _        || _        || _        || _        || _        dS )zŠInitializes HungarianMatcher with cost coefficients, Focal Loss, mask prediction, sample points, and alpha
        gamma factors.
        Né   é   é   )ÚclassÚbboxÚgiouÚmaskÚdice)ÚsuperÚ__init__Ú	cost_gainÚuse_flÚ	with_maskÚnum_sample_pointsÚalphaÚgamma)Úselfr   r   r   r   r   r   Ú	__class__s          €ú|/var/www/html/cool-property-finder/image-detection-backend/venv/lib/python3.11/site-packages/ultralytics/models/utils/ops.pyr   zHungarianMatcher.__init__"   sc   ø€ õ 	‰Œ×ÒÑÔÐØÐØ"#¨Q¸À1ÈaÐPÐPˆIØ"ˆŒØˆŒØ"ˆŒØ!2ˆÔØˆŒ
ØˆŒ
ˆ
ˆ
ó    c                 óî  ‡— |j         \  }}	}
t          ‰¦  «        dk    rd„ t          |¦  «        D ¦   «         S |                     ¦   «                              d|
¦  «        }| j        rt          j        |¦  «        nt          j        |d¬¦  «        }|                     ¦   «                              dd¦  «        }|dd…|f         }| j        red| j	        z
  || j
        z  z  d|z
  dz                        ¦   «          z  }| j	        d|z
  | j
        z  z  |dz                        ¦   «          z  }||z
  }n| }|                     d¦  «        |                     d¦  «        z
                       ¦   «                              d¦  «        }d	t          |                     d¦  «        |                     d¦  «        d
d
¬¦  «                             d¦  «        z
  }| j        d         |z  | j        d         |z  z   | j        d         |z  z   }| j        r||                      |‰||¦  «        z  }d||                     ¦   «         |                     ¦   «         z  <   |                     ||	d¦  «                             ¦   «         }d„ t-          |                     ‰d¦  «        ¦  «        D ¦   «         }t1          j        dg‰dd…         ¢¦  «                             d¦  «        Šˆfd„t-          |¦  «        D ¦   «         S )a=  
        Forward pass for HungarianMatcher. This function computes costs based on prediction and ground truth
        (classification cost, L1 cost between boxes and GIoU cost between boxes) and finds the optimal matching between
        predictions and ground truth based on these costs.

        Args:
            pred_bboxes (Tensor): Predicted bounding boxes with shape [batch_size, num_queries, 4].
            pred_scores (Tensor): Predicted scores with shape [batch_size, num_queries, num_classes].
            gt_cls (torch.Tensor): Ground truth classes with shape [num_gts, ].
            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape [num_gts, 4].
            gt_groups (List[int]): List of length equal to batch size, containing the number of ground truths for
                each image.
            masks (Tensor, optional): Predicted masks with shape [batch_size, num_queries, height, width].
                Defaults to None.
            gt_mask (List[Tensor], optional): List of ground truth masks, each with shape [num_masks, Height, Width].
                Defaults to None.

        Returns:
            (List[Tuple[Tensor, Tensor]]): A list of size batch_size, each element is a tuple (index_i, index_j), where:
                - index_i is the tensor of indices of the selected predictions (in order)
                - index_j is the tensor of indices of the corresponding selected ground truth targets (in order)
                For each batch element, it holds:
                    len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
        r   c                 óŽ   — g | ]B}t          j        g t           j        ¬ ¦  «        t          j        g t           j        ¬ ¦  «        f‘ŒCS ©©Údtype©ÚtorchÚtensorÚlong)Ú.0Ú_s     r    ú
<listcomp>z,HungarianMatcher.forward.<locals>.<listcomp>M   sB   € ÐpÐpÐpÐab•U”\ "­E¬JÐ7Ñ7Ô7½¼ÀbÕPUÔPZÐ9[Ñ9[Ô9[Ð\ÐpÐpÐpr!   éÿÿÿÿ©Údimé   Nr   g:Œ0âŽyE>ç      ð?T)ÚxywhÚGIoUr   r   r   ç        c                 ó>   — g | ]\  }}t          ||         ¦  «        ‘ŒS © r   )r+   ÚiÚcs      r    r-   z,HungarianMatcher.forward.<locals>.<listcomp>q   s)   € Ð]Ð]Ð]±4°1°aÕ(¨¨1¬Ñ.Ô.Ð]Ð]Ð]r!   c                 ó®   •— g | ]Q\  }\  }}t          j        |t           j        ¬ ¦  «        t          j        |t           j        ¬ ¦  «        ‰|         z   f‘ŒRS r$   r'   )r+   Úkr8   ÚjÚ	gt_groupss       €r    r-   z,HungarianMatcher.forward.<locals>.<listcomp>t   sd   ø€ ð 5ð 5ð 5Ù�A‘v˜˜1õ ”˜a¥u¤zÐ2Ñ2Ô2µE´LÀÍ%Ì*Ð4UÑ4UÔ4UÐXaÐbcÔXdÑ4dÐeð 5ð 5ð 5r!   )ÚshapeÚsumÚrangeÚdetachÚviewr   ÚFÚsigmoidÚsoftmaxr   r   ÚlogÚ	unsqueezeÚabsr   Úsqueezer   r   Ú
_cost_maskÚisnanÚisinfÚcpuÚ	enumerateÚsplitr(   Ú	as_tensorÚcumsum_)r   Úpred_bboxesÚpred_scoresÚ	gt_bboxesÚgt_clsr=   ÚmasksÚgt_maskÚbsÚnqÚncÚneg_cost_classÚpos_cost_classÚ
cost_classÚ	cost_bboxÚ	cost_giouÚCÚindicess        `            r    ÚforwardzHungarianMatcher.forward0   s
  ø€ ð4 !Ô&‰
ˆˆB�åˆy‰>Œ>˜QÒÐØpÐpÕfkÐlnÑfoÔfoÐpÑpÔpÐpð "×(Ò(Ñ*Ô*×/Ò/°°BÑ7Ô7ˆØ04´Ð_•a”i Ñ,Ô,Ð,ÅÄÈ;Ð\^ÐA_ÑA_ÔA_ˆà!×(Ò(Ñ*Ô*×/Ò/°°AÑ6Ô6ˆð " ! ! ! V )Ô,ˆØŒ;ð 	&Ø $¤*™n°ÀÄ
Ñ1JÑKÐQRÐU`ÑQ`ÐcgÑQg×PlÒPlÑPnÔPnÐOnÑoˆNØ!œZ¨A°©OÀÄ
Ñ+JÑKÐQ\Ð_cÑQc×PhÒPhÑPjÔPjÐOjÑkˆNØ'¨.Ñ8ˆJˆJà%˜ˆJð !×*Ò*¨1Ñ-Ô-°	×0CÒ0CÀAÑ0FÔ0FÑF×KÒKÑMÔM×QÒQÐRTÑUÔUˆ	ð �( ;×#8Ò#8¸Ñ#;Ô#;¸Y×=PÒ=PÐQRÑ=SÔ=SÐZ^ÐeiÐjÑjÔj×rÒrÐsuÑvÔvÑvˆ	ð ŒN˜7Ô# jÑ0ØŒN˜6Ô" YÑ.ñ/àŒN˜6Ô" YÑ.ñ/ˆð Œ>ð 	@Ø�—’  Y°°wÑ?Ô?Ñ?ˆAð $'ˆˆ!�'Š'‰)Œ)�a—g’g‘i”iÑ
Ñ à�FŠF�2�r˜2ÑÔ×"Ò"Ñ$Ô$ˆØ]Ð]½9ÀQÇWÂWÈYÐXZÑE[ÔE[Ñ;\Ô;\Ð]Ñ]Ô]ˆÝ”O QÐ$8¨°3°B°3¬Ð$8Ñ9Ô9×AÒAÀ!ÑDÔDˆ	ð5ð 5ð 5ð 5Ý!*¨7Ñ!3Ô!3ð5ñ 5ô 5ð 	5r!   )NTFr
   r   r   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rb   Ú__classcell__)r   s   @r    r	   r	      sc   ø€ € € € € ðð ð*ð ð ð ð ð ðE5ð E5ð E5ð E5ð E5ð E5ð E5ð E5r!   r	   éd   ç      à?r2   Fc                 ó$	  ‡"‡#— |r|dk    rdS | d         }t          |¦  «        }	t          |¦  «        Š#‰#dk    rdS |‰#z  }
|
dk    rdn|
}
t          |¦  «        }| d         }| d         }| d         }|                     d|
z  ¦  «        }|                     d|
z  d¦  «        }|                     d|
z  ¦  «                             d	¦  «        }t          j        |	|
z  t
          j        |j        ¬
¦  «        |
|	z  z   }|dk    rot          j	        |j
        ¦  «        |dz  k     }t          j        |¦  «                             d	¦  «        }t          j        |d||j        |j        ¬
¦  «        }|||<   |dk    r¾t          |¦  «        }|ddd…f         dz                       dd¦  «        |z  }t          j        |dd¦  «        dz  dz
  }t          j        |¦  «        }||xx         dz  cc<   ||z  }|||z  z  }|                     dd¬¦  «         t%          |¦  «        }t          j        |d¬¦  «        }t)          ‰#dz  |
z  ¦  «        }||         }t          j        |||j
        d	         |j        ¬¦  «        }t          j        ||d|j        ¬¦  «        }t          j        d„ |D ¦   «         ¦  «        Š"t          j        ˆ"ˆ#fd„t1          |
¦  «        D ¦   «         d¬¦  «        }t          j        ˆ"ˆ#fd„t1          d|
z  ¦  «        D ¦   «         ¦  «        Š"|||‰"f<   |||‰"f<   ||z   }t          j        ||gt
          j        ¬¦  «        }d||d…d|…f<   t1          |
¦  «        D ]˜} | dk    r#d|‰#dz  | z  ‰#dz  | dz   z  …‰#dz  | dz   z  |…f<   | |
dz
  k    r!d|‰#dz  | z  ‰#dz  | dz   z  …d‰#| z  dz  …f<   ŒUd|‰#dz  | z  ‰#dz  | dz   z  …‰#dz  | dz   z  |…f<   d|‰#dz  | z  ‰#dz  | dz   z  …d‰#dz  | z  …f<   Œ™d„ |                     ¦   «                              t9          |¦  «        d¬¦  «        D ¦   «         |
||gdœ}!|                     |j        ¦  «        |                     |j        ¦  «        |                     |j        ¦  «        |!fS )aÔ  
    Get contrastive denoising training group. This function creates a contrastive denoising training group with positive
    and negative samples from the ground truths (gt). It applies noise to the class labels and bounding box coordinates,
    and returns the modified labels, bounding boxes, attention mask and meta information.

    Args:
        batch (dict): A dict that includes 'gt_cls' (torch.Tensor with shape [num_gts, ]), 'gt_bboxes'
            (torch.Tensor with shape [num_gts, 4]), 'gt_groups' (List(int)) which is a list of batch size length
            indicating the number of gts of each image.
        num_classes (int): Number of classes.
        num_queries (int): Number of queries.
        class_embed (torch.Tensor): Embedding weights to map class labels to embedding space.
        num_dn (int, optional): Number of denoising. Defaults to 100.
        cls_noise_ratio (float, optional): Noise ratio for class labels. Defaults to 0.5.
        box_noise_scale (float, optional): Noise scale for bounding box coordinates. Defaults to 1.0.
        training (bool, optional): If it's in training mode. Defaults to False.

    Returns:
        (Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Dict]]): The modified class embeddings,
            bounding boxes, attention mask and meta information for denoising. If not in training mode or 'num_dn'
            is less than or equal to 0, the function returns None for all elements in the tuple.
    r   )NNNNr=   r   ÚclsÚbboxesÚ	batch_idxr   r.   )r&   Údeviceri   .Nr   r2   r5   )ÚminÚmaxg�íµ ÷Æ°>)Úeps)rn   r1   c                 óh   — g | ]/}t          j        t          |¦  «        t           j        ¬ ¦  «        ‘Œ0S r$   )r(   r)   r@   r*   )r+   Únums     r    r-   z!get_cdn_group.<locals>.<listcomp>ê   s/   € Ð]Ð]Ð]ÈC�Uœ\­%°©*¬*½E¼JÐGÑGÔGÐ]Ð]Ð]r!   c                 ó    •— g | ]
}‰‰|z  z   ‘ŒS r7   r7   ©r+   r8   Úmap_indicesÚmax_numss     €€r    r-   z!get_cdn_group.<locals>.<listcomp>ë   s"   ø€ ÐPÐPÐP¸!˜;¨°A©Ñ5ÐPÐPÐPr!   r/   c                 ó    •— g | ]
}‰‰|z  z   ‘ŒS r7   r7   ru   s     €€r    r-   z!get_cdn_group.<locals>.<listcomp>í   s"   ø€ ÐVÐVÐV¸A˜[¨8°a©<Ñ7ÐVÐVÐVr!   r%   Tc                 ó8   — g | ]}|                      d ¦  «        ‘ŒS )r.   )Úreshape)r+   Úps     r    r-   z!get_cdn_group.<locals>.<listcomp>ÿ   s"   € ÐZÐZÐZ¨�q—y’y ‘}”}ÐZÐZÐZr!   )Ú
dn_pos_idxÚdn_num_groupÚdn_num_split)r?   rp   ÚlenÚrepeatrB   r(   Úaranger*   rn   Úrandr>   ÚnonzerorI   Úrandint_liker&   r   Ú	rand_likeÚclip_r   ÚlogitÚintÚzerosÚcatÚstackr@   ÚboolrM   rO   ÚlistÚto)$ÚbatchÚnum_classesÚnum_queriesÚclass_embedÚnum_dnÚcls_noise_ratioÚbox_noise_scaleÚtrainingr=   Ú	total_numÚ	num_grouprX   rU   Úgt_bboxÚb_idxÚdn_clsÚdn_bboxÚdn_b_idxÚneg_idxr   ÚidxÚ	new_labelÚ
known_bboxÚdiffÚ	rand_signÚ	rand_partÚdn_cls_embedÚpadding_clsÚpadding_bboxÚpos_idxÚtgt_sizeÚ	attn_maskr8   Údn_metarv   rw   s$                                     @@r    Úget_cdn_groupr¬   –   sQ  øø€ ð> ð &˜ 1š˜Ø%Ð%Ø�kÔ"€IÝ�I‘”€IÝ�9‰~Œ~€HØ�1‚}€}Ø%Ð%à˜(Ñ"€IØ !’^�^��¨€Iå	ˆY‰Œ€BØ�5Œ\€FØ�HŒo€GØ�+Ô€Eð �]Š]˜1˜y™=Ñ)Ô)€FØ�nŠn˜Q ™]¨AÑ.Ô.€GØ�|Š|˜A 	™MÑ*Ô*×/Ò/°Ñ3Ô3€Hõ Œl˜9 yÑ0½¼
È7Ì>ÐZÑZÔZÐ]fÐirÑ]rÑr€Gà˜ÒÐåŒz˜&œ,Ñ'Ô'¨?¸SÑ+@ÒAˆÝŒm˜DÑ!Ô!×)Ò)¨"Ñ-Ô-ˆåÔ& s¨A¨{À&Ä,ÐW]ÔWdÐeÑeÔeˆ	Øˆˆs‰à˜ÒÐÝ˜wÑ'Ô'ˆ
à˜˜Q˜R˜R˜Ô  3Ñ&×.Ò.¨q°!Ñ4Ô4°ÑFˆåÔ& w°°1Ñ5Ô5¸Ñ;¸cÑAˆ	Ý”O GÑ,Ô,ˆ	Ø�'ÐÐÔ˜cÑ!ÐÐÑØ�YÑˆ	Ø�i $Ñ&Ñ&ˆ
Ø×Ò˜S cÐÑ*Ô*Ð*Ý˜JÑ'Ô'ˆÝ”+˜g¨4Ð0Ñ0Ô0ˆå�˜A‘ 	Ñ)Ñ*Ô*€Fà˜vÔ&€LÝ”+˜b &¨,Ô*<¸RÔ*@ÈÌÐWÑWÔW€KÝ”;˜r 6¨1°W´^ÐDÑDÔD€Lå”)Ð]Ð]ÐS\Ð]Ñ]Ô]Ñ^Ô^€KÝŒkÐPÐPÐPÐPÐP½uÀYÑ?OÔ?OÐPÑPÔPÐVWÐXÑXÔX€Gå”)ÐVÐVÐVÐVÐVÅÀqÈ9Á}ÑAUÔAUÐVÑVÔVÑWÔW€KØ+7€K�˜;Ð'Ñ(Ø,3€L�(˜KÐ(Ñ)à˜Ñ#€HÝ”˜X xÐ0½¼
ÐCÑCÔC€Ià"&€Iˆfˆgˆg�w˜�wÐÑå�9ÑÔð Yð YˆØ�Š6ˆ6Ø`dˆI�h ‘l QÑ& x°!¡|°q¸1±uÑ'=Ð=¸xÈ!¹|ÈqÐSTÉuÑ?UÐV\Ð?\Ð\Ñ]Ø�	˜A‘ÒÐØTXˆI�h ‘l QÑ& x°!¡|°q¸1±uÑ'=Ð=Ð?PÀÈ1ÁÈqÑ@PÐ?PÐPÑQÐQà`dˆI�h ‘l QÑ& x°!¡|°q¸1±uÑ'=Ð=¸xÈ!¹|ÈqÐSTÉuÑ?UÐV\Ð?\Ð\Ñ]ØTXˆI�h ‘l QÑ& x°!¡|°q¸1±uÑ'=Ð=Ð?PÀÈ1ÁÈqÑ@PÐ?PÐPÑQÐQàZÐZ¨g¯kªk©m¬m×.AÒ.AÅ$ÀyÁ/Ä/ÐWXÐ.AÑ.YÔ.YÐZÑZÔZØ!Ø Ð-ð/ð /€Gð
 �>Š>˜+Ô,Ñ-Ô-¨|¯ª¸{Ô?QÑ/RÔ/RÐT]×T`ÒT`ØÔñUô UØ$ð%ð %r!   )rh   ri   r2   F)r(   Útorch.nnÚnnÚtorch.nn.functionalÚ
functionalrC   Úscipy.optimizer   Úultralytics.utils.metricsr   Úultralytics.utils.opsr   r   ÚModuler	   r¬   r7   r!   r    ú<module>rµ      sà   ðð €€€Ø Ð Ð Ð Ð Ð Ø Ð Ð Ð Ð Ð Ð Ð Ð Ø 0Ð 0Ð 0Ð 0Ð 0Ð 0à .Ð .Ð .Ð .Ð .Ð .Ø 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6Ð 6ði5ð i5ð i5ð i5ð i5�r”yñ i5ô i5ð i5ð\ Ø"%Ø"%Ø ðn%ð n%ð n%ð n%ð n%ð n%r!   