o
    پiN                     @   s  d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dl	Z	d dl
mZ d dlm  mZ z
d dlmZ dZW n eyD   dZY nw d dlmZ d dlZg dZG dd	 d	ZG d
d dZG dd dejZG dd dZeedrejjdejjdejjdejj dejj!dejj"diZ#nejdejdejdej dej!dej"diZ#dd e#$ D Z%erejdejdejdej dej!dej"diZ&dd e&$ D Z'ni Z(i Z&dd Z)dd Z*dd Z+e*de*dfZ,d=d!d"Z-G d#d$ d$Z.	 	%d>d&e	j/d'ee0ee0 f d(ee0ee0e0e0f f d)e1d*e	j/f
d+d,Z2G d-d. d.e	j3j4Z5	 	%d>d&e	j/d/e0d0e0d1e0d2e0d(ee0ee0e0e0f f d)e1d*e	j/fd3d4Z6G d5d6 d6e	j3j4Z7G d7d8 d8Z8G d9d: d:Z9G d;d< d<e	j3j4Z:dS )?    N)ListSequenceTupleUnion)InterpolationModeTF)Image)ToNumpyToTensorstr_to_interp_modestr_to_pil_interpinterp_mode_to_str!RandomResizedCropAndInterpolationCenterCropOrPadcenter_crop_or_padcrop_or_padRandomCropOrPad	RandomPadResizeKeepRatio
TrimBorderMaybeToTensorMaybePILToTensorc                   @   s   e Zd Zdd ZdS )r   c                 C   s8   t j|t jd}|jdk rt j|dd}t |d}|S )Ndtype   )axis   )nparrayuint8ndimexpand_dimsrollaxis)selfpil_imgnp_img r&   H/home/ubuntu/.local/lib/python3.10/site-packages/timm/data/transforms.py__call__   s
   
zToNumpy.__call__N)__name__
__module____qualname__r(   r&   r&   r&   r'   r      s    r   c                   @   s&   e Zd ZdZejfddZdd ZdS )r	   z% ToTensor with no rescaling of valuesc                 C   s
   || _ d S Nr   )r#   r   r&   r&   r'   __init__%   s   
zToTensor.__init__c                 C   s   t |j| jdS )Nr   )Fpil_to_tensortor   )r#   r$   r&   r&   r'   r(   (   s   zToTensor.__call__N)r)   r*   r+   __doc__torchfloat32r-   r(   r&   r&   r&   r'   r	   #   s    r	   c                       s@   e Zd ZdZd
 fddZdejfddZdefdd	Z	  Z
S )r   zFConvert a PIL Image or ndarray to tensor if it's not already one.
    returnNc                       t    d S r,   superr-   r#   	__class__r&   r'   r-   0      zMaybeToTensor.__init__c                 C      t |tjr|S t|S )z
        Args:
            pic (PIL Image or numpy.ndarray): Image to be converted to tensor.

        Returns:
            Tensor: Converted image.
        )
isinstancer2   Tensorr.   	to_tensorr#   picr&   r&   r'   r(   3   s   
zMaybeToTensor.__call__c                 C      | j j dS Nz()r:   r)   r8   r&   r&   r'   __repr__?   r;   zMaybeToTensor.__repr__r4   N)r)   r*   r+   r1   r-   r2   r>   r(   strrE   __classcell__r&   r&   r9   r'   r   ,   s
    r   c                       s8   e Zd ZdZd
 fddZdd Zdefdd	Z  ZS )r   zSConvert a PIL Image to a tensor of the same type - this does not scale values.
    r4   Nc                    r5   r,   r6   r8   r9   r&   r'   r-   G   r;   zMaybePILToTensor.__init__c                 C   r<   )z
        Note: A deep copy of the underlying array is performed.

        Args:
            pic (PIL Image): Image to be converted to tensor.

        Returns:
            Tensor: Converted image.
        )r=   r2   r>   r.   r/   r@   r&   r&   r'   r(   J   s   

zMaybePILToTensor.__call__c                 C   rB   rC   rD   r8   r&   r&   r'   rE   X   r;   zMaybePILToTensor.__repr__rF   )	r)   r*   r+   r1   r-   r(   rG   rE   rH   r&   r&   r9   r'   r   C   s
    r   
Resamplingnearestbilinearbicubicboxhamminglanczosc                 C      i | ]\}}||qS r&   r&   .0abr&   r&   r'   
<dictcomp>r       rU   c                 C   rP   r&   r&   rQ   r&   r&   r'   rU   ~   rV   c                 C   s   t |  S r,   )_str_to_pil_interpolationmode_strr&   r&   r'   r      s   r   c                 C      t rt|  S t|  S r,   )has_interpolation_mode_str_to_torch_interpolationrW   rX   r&   r&   r'   r
         r
   c                 C   rZ   r,   )r[   _torch_interpolation_to_str_pil_interpolation_to_str)moder&   r&   r'   r      r]   r   3Please provide only two dimensions (h, w) for size.c                 C   sZ   t | tjrt| t| fS t | tr!t| dkr!| d | d fS t| dkr+t|| S )N   r   r   )r=   numbersNumberintr   len
ValueError)size	error_msgr&   r&   r'   _setup_size   s   rj   c                   @   s<   e Zd ZdZ			dddZedd Zd	d
 Zdd ZdS )r   aY  Crop the given PIL Image to random size and aspect ratio with random interpolation.

    A crop of random size (default: of 0.08 to 1.0) of the original size and a random
    aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
    is finally resized to given size.
    This is popularly used to train the Inception networks.

    Args:
        size: expected output size of each edge
        scale: range of size of the origin size cropped
        ratio: range of aspect ratio of the origin aspect ratio cropped
        interpolation: Default: PIL.Image.BILINEAR
    g{Gz?      ?g      ?gUUUUUU?rK   c                 C   sx   t |ttfrt|| _n||f| _|d |d ks"|d |d kr'td |dkr/t| _nt|| _|| _	|| _
d S )Nr   rb   z"range should be of kind (min, max)random)r=   listtuplerh   warningswarn_RANDOM_INTERPOLATIONinterpolationr
   scaleratio)r#   rh   ru   rv   rt   r&   r&   r'   r-      s   
 


z*RandomResizedCropAndInterpolation.__init__c                 C   sJ  t | \}}|| }tdD ]U}tj| | }t|d t|d f}ttj| }	tt	t
||	 }
tt	t
||	 }|
|krd||krdtd|| }td||
 }||||
f  S q|| }|t|k r||}
tt	|
t| }n|t|kr|}tt	|t| }
n|}
|}|| d }||
 d }||||
fS )a  Get parameters for ``crop`` for a random sized crop.

        Args:
            img (PIL Image): Image to be cropped.
            scale (tuple): range of size of the origin size cropped
            ratio (tuple): range of aspect ratio of the origin aspect ratio cropped

        Returns:
            tuple: params (i, j, h, w) to be passed to ``crop`` for a random
                sized crop.
        
   r   rb   r   )r.   get_image_sizerangern   uniformmathlogexpre   roundsqrtrandintminmax)imgru   rv   img_wimg_hareaattempttarget_area	log_ratioaspect_ratiotarget_wtarget_hijin_ratior&   r&   r'   
get_params   s2   z,RandomResizedCropAndInterpolation.get_paramsc              	   C   sV   |  || j| j\}}}}t| jttfrt| j}n| j}t	
|||||| j|S )z
        Args:
            img (PIL Image): Image to be cropped and resized.

        Returns:
            PIL Image: Randomly cropped and resized image.
        )r   ru   rv   r=   rt   rp   ro   rn   choicer.   resized_croprh   )r#   r   r   r   hwrt   r&   r&   r'   r(      s
   z*RandomResizedCropAndInterpolation.__call__c                 C   s   t | jttfrddd | jD }nt| j}| jjd| j	 }|dtdd | j
D 7 }|dtd	d | jD 7 }|d
|7 }|S )N c                 S      g | ]}t |qS r&   r   rR   xr&   r&   r'   
<listcomp>      z>RandomResizedCropAndInterpolation.__repr__.<locals>.<listcomp>	(size={0}z, scale={0}c                 s       | ]}t |d V  qdS    Nr~   )rR   sr&   r&   r'   	<genexpr>
      z=RandomResizedCropAndInterpolation.__repr__.<locals>.<genexpr>z, ratio={0}c                 s   r   r   r   )rR   rr&   r&   r'   r     r   z, interpolation={0}))r=   rt   rp   ro   joinr   r:   r)   formatrh   ru   rv   r#   interpolate_strformat_stringr&   r&   r'   rE     s   
z*RandomResizedCropAndInterpolation.__repr__N)rk   rm   rK   	r)   r*   r+   r1   r-   staticmethodr   r(   rE   r&   r&   r&   r'   r      s    

*r   constantr   output_sizefillpadding_moder4   c                 C   s  t |}|\}}t| \}}}||ks||kre||kr"|| d nd||kr-|| d nd||kr:|| d d nd||krG|| d d ndg}	tj| |	||d} t| \}}}||kre||kre| S tt|| d }
tt|| d }t| |
|||S )ak  Center crops and/or pads the given image.

    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
    If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.

    Args:
        img (PIL Image or Tensor): Image to be cropped.
        output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
            it is used for both directions.
        fill (int, Tuple[int]): Padding color

    Returns:
        PIL Image or Tensor: Cropped image.
    r   r   rb   r   r   g       @)rj   r.   get_dimensionspadre   r~   crop)r   r   r   r   crop_height
crop_width_image_heightimage_widthpadding_ltrbcrop_top	crop_leftr&   r&   r'   r     s    r   c                
       sh   e Zd ZdZ		ddeeee f deeeeeef f def fddZ	d	d
 Z
defddZ  ZS )r   a/  Crops the given image at the center.
    If the image is torch Tensor, it is expected
    to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
    If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.

    Args:
        size (sequence or int): Desired output size of the crop. If size is an
            int instead of sequence like (h, w), a square crop (size, size) is
            made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
    r   r   rh   r   r   c                    $   t    t|| _|| _|| _d S r,   r7   r-   rj   rh   r   r   r#   rh   r   r   r9   r&   r'   r-   F     


zCenterCropOrPad.__init__c                 C   s   t || j| j| jdS )
        Args:
            img (PIL Image or Tensor): Image to be cropped.

        Returns:
            PIL Image or Tensor: Cropped image.
        r   )r   rh   r   r   )r#   r   r&   r&   r'   forwardQ  s   zCenterCropOrPad.forwardr4   c                 C      | j j d| j dS Nz(size=)r:   r)   rh   r8   r&   r&   r'   rE   [     zCenterCropOrPad.__repr__r   r   )r)   r*   r+   r1   r   re   r   r   rG   r-   r   rE   rH   r&   r&   r9   r'   r   :  s    
r   topleftheightwidthc                 C   s   t | \}}}	|| }
|| }|dk s |dk s |
|	ks ||krQt| td|
 dt| td| dt|
t|	| dt|t|| dg}t j| |||d} t|d}t|d}t | ||||S )z[ Crops and/or pads image to meet target size, with control over fill and padding_mode.
    r   r   )r.   r   r   r   r   r   )r   r   r   r   r   r   r   r   r   r   rightbottomr   r&   r&   r'   r   _  s    

r   c                
       st   e Zd ZdZ		ddeeee f deeeeeef f def fddZ	e
d	d
 Zdd ZdefddZ  ZS )r   zP Crop and/or pad image with random placement within the crop or pad margin.
    r   r   rh   r   r   c                    r   r,   r   r   r9   r&   r'   r-     r   zRandomCropOrPad.__init__c           	      C   sh   t | \}}}||d  }||d  }tttdt||}tttdt||}||fS )Nr   rb   )r.   r   re   r{   copysignrn   r   abs)	r   rh   r   r   r   delta_heightdelta_widthr   r   r&   r&   r'   r     s   zRandomCropOrPad.get_paramsc              	   C   s8   |  || j\}}t|||| jd | jd | j| jdS )r   r   rb   )r   r   r   r   r   r   )r   rh   r   r   r   )r#   r   r   r   r&   r&   r'   r     s   zRandomCropOrPad.forwardr4   c                 C   r   r   r   r8   r&   r&   r'   rE     r   zRandomCropOrPad.__repr__r   )r)   r*   r+   r1   r   re   r   r   rG   r-   r   r   r   rE   rH   r&   r&   r9   r'   r   {  s    
r   c                   @   s*   e Zd Zd	ddZedd Zdd ZdS )
r   r   c                 C   s   || _ || _d S r,   )
input_sizer   )r#   r   r   r&   r&   r'   r-     s   
zRandomPad.__init__c           
      C   sf   t | \}}t|d | d}t|d | d}td|}td|}|| }|| }	||||	fS )Nrb   r   )r.   rx   r   rn   r   )
r   r   r   r   r   r   pad_leftpad_top	pad_right
pad_bottomr&   r&   r'   r     s   zRandomPad.get_paramsc                 C   s"   |  || j}t||| j}|S r,   )r   r   r.   r   r   )r#   r   paddingr&   r&   r'   r(     s   zRandomPad.__call__N)r   )r)   r*   r+   r-   r   r   r(   r&   r&   r&   r'   r     s
    


r   c                   @   sP   e Zd ZdZ							dddZe						dd
dZdd Zdd ZdS )r   z" Resize and Keep Aspect Ratio
            rK   g333333?g?Fg?g(\?c	           	      C   sj   t |ttfrt|| _n||f| _|dkrt| _nt|| _t|| _|| _	|| _
|| _|| _|| _dS )z

        Args:
            size:
            longest:
            interpolation:
            random_scale_prob:
            random_scale_range:
            random_scale_area:
            random_aspect_prob:
            random_aspect_range:
        rn   N)r=   ro   rp   rh   rs   rt   r
   floatlongestrandom_scale_probrandom_scale_rangerandom_scale_arearandom_aspect_probrandom_aspect_range)	r#   rh   r   rt   r   r   r   r   r   r&   r&   r'   r-     s   



zResizeKeepRatio.__init__rl   gHzG?c                    s  t | dd  \}}	}
|\}}|| }|	| }t||| t||d|    |dkrKt |k rKt|d |d }|rFdt| }||f}nd}|dkr~t |k r~t|d t|d f}t	tj| }t|}|d | |d | f} fddt
|
|D }|S )zGet parameters
        rb   Nrl   r   )rl   rl   c                    s    g | ]\}}t ||   qS r&   r   )rR   r   frv   r&   r'   r     s     z.ResizeKeepRatio.get_params.<locals>.<listcomp>)r.   r   r   r   rn   rz   r{   r   r|   r}   zip)r   target_sizer   r   r   r   r   r   r   r   img_sizer   r   ratio_hratio_wratio_factor
log_aspectaspect_factorrh   r&   r   r'   r     s$    

zResizeKeepRatio.get_paramsc              
   C   s\   |  || j| j| j| j| j| j| j}t| j	t
tfr"t| j	}n| j	}t|||}|S )z
        Args:
            img (PIL Image): Image to be cropped and resized.

        Returns:
            PIL Image: Resized, padded to at least target size, possibly cropped to exactly target size
        )r   rh   r   r   r   r   r   r   r=   rt   rp   ro   rn   r   r.   resize)r#   r   rh   rt   r&   r&   r'   r(     s   
zResizeKeepRatio.__call__c                 C   s   t | jttfrddd | jD }nt| j}| jjd| j	 }|d| 7 }|d| j
d7 }|d| jd7 }|d	| jd
 dd| jd dd7 }|d| jd7 }|d| jd
 dd| jd dd7 }|S )Nr   c                 S   r   r&   r   r   r&   r&   r'   r   (  r   z,ResizeKeepRatio.__repr__.<locals>.<listcomp>r   z, interpolation=z
, longest=z.3fz, random_scale_prob=z, random_scale_range=(r   z, rb   r   z, random_aspect_prob=z, random_aspect_range=(z)))r=   rt   rp   ro   r   r   r:   r)   r   rh   r   r   r   r   r   r   r&   r&   r'   rE   &  s&   






zResizeKeepRatio.__repr__N)r   rK   r   r   Fr   r   )r   r   Fr   r   r   r&   r&   r&   r'   r     s&    
&'r   c                       s*   e Zd Zdef fddZdd Z  ZS )r   border_sizec                    s   t    || _d S r,   )r7   r-   r   )r#   r   r9   r&   r'   r-   9  s   

zTrimBorder.__init__c                 C   sf   t |\}}| j }}t||}t||}td|d| j  }td|d| j  }t |||||S )Nr   r   )r.   rx   r   r   r   r   )r#   r   r   r   r   r   r   r   r&   r&   r'   r   @  s   


zTrimBorder.forward)r)   r*   r+   re   r-   r   rH   r&   r&   r9   r'   r   7  s
    r   )ra   r   );r{   rc   rn   rq   typingr   r   r   r   r2   torchvision.transforms
transforms!torchvision.transforms.functional
functionalr.   r   r[   ImportErrorPILr   numpyr   __all__r   r	   r   r   hasattrrI   NEARESTBILINEARBICUBICBOXHAMMINGLANCZOSr_   itemsrW   r^   r\   _pil_interpolation_to_torchr   r
   r   rs   rj   r   r>   re   rG   r   nnModuler   r   r   r   r   r   r&   r&   r&   r'   <module>   s    
	

	
m
*+
/w