o
    oi                     @   s   d dl Z d dlmZmZmZmZmZmZ d dlm	Z
 d dlmZ d dlmZmZ d dlmZmZmZ d dlmZmZ G dd	 d	eZdS )
    N)AnyDictListOptionalTupleUnion)random_generator)MixAugmentationBaseV2)DataKeyDType)Tensorstackzeros)bbox_to_maskinfer_bbox_shapec                       s  e Zd ZdZ								ddedeeeee	e	f f  deeee	f  d	e
d
e	de
deeeeeef   de
ddf fddZdedeeef deeef defddZ	ddedeeef deeeef  defddZ	ddedeeef deeeef  defddZ  ZS )RandomCutMixV2aC  Apply CutMix augmentation to a batch of tensor images.

    .. image:: _static/img/RandomCutMixV2.png

    Implementation for `CutMix: Regularization Strategy to Train Strong Classifiers with
    Localizable Features` :cite:`yun2019cutmix`.

    The function returns (inputs, labels), in which the inputs is the tensor that contains the mixup images
    while the labels is a :math:`(\text{num_mixes}, B, 3)` tensor that contains (label_permuted_batch, lambda)
    for each cutmix.

    The implementation referred to the following repository: `https://github.com/clovaai/CutMix-PyTorch
    <https://github.com/clovaai/CutMix-PyTorch>`_.

    Args:
        height: the width of the input image.
        width: the width of the input image.
        p: probability for applying an augmentation to a batch. This param controls the augmentation
                   probabilities batch-wisely.
        num_mix: cut mix times.
        beta: hyperparameter for generating cut size from beta distribution.
            Beta cannot be set to 0 after torch 1.8.0. If None, it will be set to 1.
        cut_size: controlling the minimum and maximum cut ratio from [0, 1].
            If None, it will be set to [0, 1], which means no restriction.
        same_on_batch: apply the same transformation across the batch.
            This flag will not maintain permutation order.
        keepdim: whether to keep the output shape the same as input (True) or broadcast it
                        to the batch form (False).
        use_correct_lambda: if True, compute lambda according to the CutMix paper
            (`lam = 1 - area_ratio`). Defaults to False (`lam = area_ratio`) for backward compatibility,
            but will raise a deprecation warning when False.

    Inputs:
        - Input image tensors, shape of :math:`(B, C, H, W)`.
        - Raw labels, shape of :math:`(B)`.

    Returns:
        Tuple[Tensor, Tensor]:
        - Adjusted image, shape of :math:`(B, C, H, W)`.
        - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, num_mix, 3)`.

    Note:
        This implementation would randomly cutmix images in a batch. Ideally, the larger batch size would be preferred.

    Examples:
        >>> rng = torch.manual_seed(3)
        >>> input = torch.rand(2, 1, 3, 3)
        >>> input[0] = torch.ones((1, 3, 3))
        >>> label = torch.tensor([0, 1])
        >>> cutmix = RandomCutMixV2(data_keys=["input", "class"])
        >>> cutmix(input, label)
        [tensor([[[[0.8879, 0.4510, 1.0000],
                  [0.1498, 0.4015, 1.0000],
                  [1.0000, 1.0000, 1.0000]]],
        <BLANKLINE>
        <BLANKLINE>
                [[[1.0000, 1.0000, 0.7995],
                  [1.0000, 1.0000, 0.0542],
                  [0.4594, 0.1756, 0.9492]]]]), tensor([[[0.0000, 1.0000, 0.4444],
                 [1.0000, 0.0000, 0.4444]]])]

       NF      ?num_mixcut_sizebetasame_on_batchpkeepdim	data_keysuse_correct_lambdareturnc	           	         sN   t  jd||||d tj||||d| _|| _| js%tjdtdd d S d S )Nr   )r   p_batchr   r   r   )r   zRandomCutMixV2 currently uses the old (inconsistent) lambda computation. Set `use_correct_lambda=True` to align with the original CutMix paper. This default will change in a future release.   )
stacklevel)	super__init__rgCutmixGenerator_param_generatorr   warningswarnDeprecationWarning)	selfr   r   r   r   r   r   r   r   	__class__ V/home/ubuntu/.local/lib/python3.10/site-packages/kornia/augmentation/_2d/mix/cutmix.pyr!   [   s   
zRandomCutMixV2.__init__inputparamsflagsc                 C   s   |d \}}g }t |d |d D ]f\}}|jd||jd}	t|\}
}|
|j||j ||  }| jr=d| n|}|t|j|jt	
t|d  d|	j|jt	
t|d  d|j|jt	
t|d  dgd qt|dS )	Nimage_shape	mix_pairscrop_srcr   dimindexr   dtypedevicer6   )zipindex_selecttor8   r   r6   r   appendr   r   to_torchintitem)r(   r-   r.   r/   heightwidth
out_labelspaircroplabels_permutewhlam_vallamr+   r+   r,   apply_transform_classs   s"       
z$RandomCutMixV2.apply_transform_classc                 C   s   g }t t||jtt|d  d}t| jj	D ]+}|
t|j|jtt|d  d|j|jtt|d  d|gd qt|dS )Nr6   r7   r   r   )r   lenr8   r   r=   r>   r?   ranger$   r   r<   r   r;   )r(   r-   r.   r/   rB   rI   _r+   r+   r,   apply_non_transform_class   s   &  
z(RandomCutMixV2.apply_non_transform_classmaybe_flagsc                 C   s   | d| d}}| }t|d |d D ]*\}}|jd||jd}	t||| jdd	d| ddd}
|	|
 ||
< q|S )	Nr      r1   r2   r   r3   r   )r4   )
sizecloner9   r:   r;   r8   r   bool	unsqueezerepeat)r(   r-   r.   rO   r@   rA   
out_inputsrC   rD   input_permutemaskr+   r+   r,   apply_transform   s   *zRandomCutMixV2.apply_transform)r   NNFr   FNF)N)__name__
__module____qualname____doc__r>   r   r   r   r   floatrS   r   strr
   r!   r   r   rJ   rN   rY   __classcell__r+   r+   r)   r,   r      sd    A	
*


r   )r%   typingr   r   r   r   r   r   kornia.augmentationr   r"    kornia.augmentation._2d.mix.baser	   kornia.constantsr
   r   kornia.corer   r   r   kornia.geometry.bboxr   r   r   r+   r+   r+   r,   <module>   s    