U
    h8?                     @   s  d dl Z d dlZd dlZd dlmZmZmZmZmZm	Z	m
Z
mZ d dlZd dlZd dlmZ d dlmZmZ d dlmZmZ d dlmZ ddlmZmZ dd	lmZm Z m!Z!m"Z"m#Z#m$Z$ G d
d deZ%G dd deZ&G dd de&Z'G dd de&Z(G dd deZ)dS )    N)AnyCallableDictListOptionalSequenceTupleUnion)one_hot)tree_flattentree_unflatten)
transforms
tv_tensors)
functional   )_RandomApplyTransform	Transform)_check_sequence_input_parse_labels_getterhas_anyis_pure_tensor	query_chw
query_sizec                       s   e Zd ZdZejZeee	f d fddZ
deeeef eeef eed
 fddZee	e	e	e	d fddZee	 eee	f dddZe	eee	f e	dddZ  ZS )RandomErasingaN  Randomly select a rectangle region in the input image or video and erase its pixels.

    This transform does not support PIL Image.
    'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896

    Args:
        p (float, optional): probability that the random erasing operation will be performed.
        scale (tuple of float, optional): range of proportion of erased area against input image.
        ratio (tuple of float, optional): range of aspect ratio of erased area.
        value (number or tuple of numbers): erasing value. Default is 0. If a single int, it is used to
            erase all pixels. If a tuple of length 3, it is used to erase
            R, G, B channels respectively.
            If a str of 'random', erasing each pixel with random values.
        inplace (bool, optional): boolean to make this transform inplace. Default set to False.

    Returns:
        Erased input.

    Example:
        >>> from torchvision.transforms import v2 as transforms
        >>>
        >>> transform = transforms.Compose([
        >>>   transforms.RandomHorizontalFlip(),
        >>>   transforms.PILToTensor(),
        >>>   transforms.ConvertImageDtype(torch.float),
        >>>   transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
        >>>   transforms.RandomErasing(),
        >>> ])
    )returnc                    s"   t t  | jd krdn| jdS )Nrandom)value)dictsuper _extract_params_for_v1_transformr   )self	__class__ T/var/www/html/venv/lib/python3.8/site-packages/torchvision/transforms/v2/_augment.pyr   2   s    z.RandomErasing._extract_params_for_v1_transform      ?g{Gz?gQ?g333333?gffffff
@        F)pscaleratior   inplacec                    s:  t  j|d t|tjtttfs*tdt|trD|dkrDt	dt|ttfsZtdt|ttfsptd|d |d ks|d |d krt
d	 |d dk s|d dkrt	d
|| _|| _t|ttfrt|g| _n:t|trd | _n(t|ttfrdd |D | _n|| _|| _tt| j| _d S )N)r)   z=Argument value should be either a number or str or a sequencer   z&If value is str, it should be 'random'zScale should be a sequencezRatio should be a sequencer   r   z,Scale and ratio should be of kind (min, max)zScale should be between 0 and 1c                 S   s   g | ]}t |qS r#   )float).0vr#   r#   r$   
<listcomp>T   s     z*RandomErasing.__init__.<locals>.<listcomp>)r   __init__
isinstancenumbersNumberstrtuplelist	TypeError
ValueErrorwarningswarnr*   r+   intr-   r   r,   torchlogtensor
_log_ratio)r    r)   r*   r+   r   r,   r!   r#   r$   r1   8   s0     

zRandomErasing.__init__)r   inptargskwargsr   c                    sJ   t |tjtjfr4tt| j dt|j d t j	||f||S )Nz:() is currently passing through inputs of type tv_tensors.z(. This will likely change in the future.)
r2   r   BoundingBoxesMaskr:   r;   type__name__r   _call_kernel)r    r   rA   rB   rC   r!   r#   r$   rH   [   s
    zRandomErasing._call_kernelflat_inputsr   c                 C   s  t |\}}}| jd k	r:t| jd|fkr:td| d|| }| j}tdD ]}|td| j	d | j	d 
  }ttd|d |d 
 }	ttt||	 }
ttt||	 }|
|k rP||k sqP| jd krtj||
|gtjd }nt| jd d d d f }tjd||
 d dd
 }tjd|| d dd
 } qxqPdd||d f\}}}
}}t|||
||d	S )
Nr   z@If value is a sequence, it should have either a single value or z (number of inpt channels)
   r   )dtyper   size)ijhwr/   )r   r   lenr9   r@   ranger=   emptyZuniform_r*   itemexpr<   roundmathsqrtZfloat32Znormal_r?   randintr   )r    rJ   Zimg_cZimg_hZimg_wZareaZ	log_ratio_Z
erase_areaZaspect_ratiorR   rS   r/   rP   rQ   r#   r#   r$   _get_paramsc   s6    
&
zRandomErasing._get_paramsrA   paramsr   c                 C   s,   |d d k	r(| j tj|f|d| ji}|S )Nr/   r,   )rH   FZeraser,   r    rA   r`   r#   r#   r$   
_transform   s    zRandomErasing._transform)r%   r&   r'   r(   F)rG   
__module____qualname____doc___transformsr   Z_v1_transform_clsr   r5   r   r   r-   r   boolr1   r   rH   r   r^   rc   __classcell__r#   r#   r!   r$   r      s$        

#&r   c                       sd   e Zd Zddddeee dd fddZdd	 Zej	ed
ddZ
ej	eej	dddZ  ZS )_BaseMixUpCutMix      ?Ndefault)alphanum_classeslabels_getter)rm   rn   r   c                   sH   t    t|| _tjt|gt|g| _|| _	t
|| _d S N)r   r1   r-   rm   r=   distributionsBetar?   _distrn   r   _labels_getter)r    rm   rn   ro   r!   r#   r$   r1      s
    

 z_BaseMixUpCutMix.__init__c                    sh  t |dkr|n|d }t|\}}|}t|tjjtjtjrXt	t
j d| t tjst	dt
  d jdkrt	d j d jdkrjd k	r jd	 jkrt	d
 jd	  dj d jdkrjd krt	d  jd ddd t||D d|t fddt|D < fddt||D }t||S )Nr   r   z9() does not support PIL images, bounding boxes and masks.z%The labels must be a tensor, but got z	 instead.)r      zlabels should be index based with shape (batch_size,) or probability based with shape (batch_size, num_classes), but got a tensor of shape ru   zYWhen passing 2D labels, the number of elements in last dimension must match num_classes:  != z$. You can Leave num_classes to None.z=num_classes must be passed if the labels are index-based (1D))labels
batch_sizec                 S   s   g | ]\}}|r|qS r#   r#   r.   rA   Zneeds_transformr#   r#   r$   r0      s      z,_BaseMixUpCutMix.forward.<locals>.<listcomp>Tc                 3   s   | ]\}}| kr|V  qd S rp   r#   )r.   idxrA   )rx   r#   r$   	<genexpr>   s      z+_BaseMixUpCutMix.forward.<locals>.<genexpr>c                    s$   g | ]\}}|r | n|qS r#   )rc   rz   )r`   r    r#   r$   r0      s   )rT   r   Z_needs_transform_listr   PILImager   rD   rE   r9   rF   rG   rt   r2   r=   Tensorndimshapern   r^   zipnext	enumerater   )r    inputsrJ   specZneeds_transform_listZflat_outputsr#   )rx   r`   r    r$   forward   s<    


$
z_BaseMixUpCutMix.forward)rA   ry   c                C   sd   t |tjrdnd}|j|kr6td| d|j d|jd |kr`td|jd  d| d	d S )
N      zExpected a batched input with z dims, but got z dimensions instead.r   zRThe batch size of the image or video does not match the batch size of the labels: rw   .)r2   r   Videor   r9   r   )r    rA   ry   Zexpected_num_dimsr#   r#   r$   _check_image_or_video   s    
z&_BaseMixUpCutMix._check_image_or_video)labellamr   c                C   sJ   |j dkrt|| jd}|jjs(| }|ddd| |	|S )Nr   )rn   r   rk   )
r   r
   rn   rL   Zis_floating_pointr-   rollmul_add_mul)r    r   r   r#   r#   r$   _mixup_label   s
    
z_BaseMixUpCutMix._mixup_label)rG   rd   re   r-   r   r<   r1   r   r=   r   r   r   ri   r#   r#   r!   r$   rj      s   $	-rj   c                   @   sF   e Zd ZdZee eeef dddZeeeef edddZ	dS )	MixUpa  Apply MixUp to the provided batch of images and labels.

    Paper: `mixup: Beyond Empirical Risk Minimization <https://arxiv.org/abs/1710.09412>`_.

    .. note::
        This transform is meant to be used on **batches** of samples, not
        individual images. See
        :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
        examples.
        The sample pairing is deterministic and done by matching consecutive
        samples in the batch, so the batch needs to be shuffled (this is an
        implementation detail, not a guaranteed convention.)

    In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
    into a tensor of shape ``(batch_size, num_classes)``.

    Args:
        alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
        num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding.
            Can be None only if the labels are already one-hot-encoded.
        labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
            By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
            common scenario where this transform is called as ``MixUp()(imgs_batch, labels_batch)``.
            It can also be a callable that takes the same input as the transform, and returns the labels.
    rI   c                 C   s   t t| jddS )Nr#   r   )r   r-   rs   sample)r    rJ   r#   r#   r$   r^      s    zMixUp._get_paramsr_   c                 C   s   |d }||d kr"| j ||dS t|tjtjfs<t|r| j||d d |ddd| 	|
|}t|tjtjfrtj||d	}|S |S d S )
Nr   rx   r   ry   ry   r   r   rk   like)r   r2   r   r~   r   r   r   r   r   r   r   wrap)r    rA   r`   r   outputr#   r#   r$   rc      s    "zMixUp._transformN
rG   rd   re   rf   r   r   r   r5   r^   rc   r#   r#   r#   r$   r      s   r   c                   @   sF   e Zd ZdZee eeef dddZeeeef edddZ	dS )	CutMixa  Apply CutMix to the provided batch of images and labels.

    Paper: `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features
    <https://arxiv.org/abs/1905.04899>`_.

    .. note::
        This transform is meant to be used on **batches** of samples, not
        individual images. See
        :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
        examples.
        The sample pairing is deterministic and done by matching consecutive
        samples in the batch, so the batch needs to be shuffled (this is an
        implementation detail, not a guaranteed convention.)

    In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
    into a tensor of shape ``(batch_size, num_classes)``.

    Args:
        alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
        num_classes (int, optional): number of classes in the batch. Used for one-hot-encoding.
            Can be None only if the labels are already one-hot-encoded.
        labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
            By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
            common scenario where this transform is called as ``CutMix()(imgs_batch, labels_batch)``.
            It can also be a callable that takes the same input as the transform, and returns the labels.
    rI   c                 C   s   t | jd}t|\}}tj|dd}tj|dd}dtd|  }t|| }t|| }	ttj	|| dd}
ttj	||	 dd}ttj	|| |d}ttj	||	 |d}|
|||f}t d||
 ||  ||   }t
||d	S )
Nr#   rM   rN   r%   rk   r   )min)max)boxlam_adjusted)r-   rs   r   r   r=   r\   rZ   r[   r<   clampr   )r    rJ   r   HWZr_xZr_yrZr_w_halfZr_h_halfx1y1x2y2r   r   r#   r#   r$   r^   '  s     zCutMix._get_paramsr_   c           	      C   s   ||d kr| j ||d dS t|tjtjfs8t|r| j||d d |d \}}}}|dd}| }|d	||||f |d	||||f< t|tjtjfrtj	||d
}|S |S d S )Nrx   r   r   ry   r   r   r   r   .r   )
r   r2   r   r~   r   r   r   r   cloner   )	r    rA   r`   r   r   r   r   Zrolledr   r#   r#   r$   rc   =  s    (zCutMix._transformNr   r#   r#   r#   r$   r     s   r   c                       sh   e Zd ZdZeeee f d fddZee	 e
ee	f dddZe	e
ee	f e	dd	d
Z  ZS )JPEGa>  Apply JPEG compression and decompression to the given images.

    If the input is a :class:`torch.Tensor`, it is expected
    to be of dtype uint8, on CPU, and have [..., 3 or 1, H, W] shape,
    where ... means an arbitrary number of leading dimensions.

    Args:
        quality (sequence or number): JPEG quality, from 1 to 100. Lower means more compression.
            If quality is a sequence like (min, max), it specifies the range of JPEG quality to
            randomly select from (inclusive of both ends).

    Returns:
        image with JPEG compression.
    qualityc                    s   t    t|tr||g}nt|ddd d|d   krR|d   krRdkrrn nt|d trrt|d tstd||| _d S )Nr   )ru   )Z	req_sizesr   r   d   z7quality must be an integer from 1 to 100, got quality =)r   r1   r2   r<   r   r9   r   )r    r   r!   r#   r$   r1   `  s    


FzJPEG.__init__rI   c                 C   s,   t | jd | jd d d }t|dS )Nr   r   r#   r   )r=   r\   r   rW   r   )r    rJ   r   r#   r#   r$   r^   l  s    "zJPEG._get_paramsr_   c                 C   s   | j tj||d dS )Nr   r   )rH   ra   Zjpegrb   r#   r#   r$   rc   p  s    zJPEG._transform)rG   rd   re   rf   r	   r<   r   r1   r   r   r   r5   r^   rc   ri   r#   r#   r!   r$   r   P  s   r   )*rZ   r3   r:   typingr   r   r   r   r   r   r   r	   Z	PIL.Imager}   r=   Ztorch.nn.functionalr
   Ztorch.utils._pytreer   r   Ztorchvisionr   rg   r   Ztorchvision.transforms.v2r   ra   rc   r   r   Z_utilsr   r   r   r   r   r   r   rj   r   r   r   r#   r#   r#   r$   <module>   s    ( K0E