a
    d#                     @   s   d Z ddlm  mZ ddlZdZdZejj	  dd	d
Z
dd Zdd Zdd Zdd ZedfddZedfddZddedfddZG dd dZdS )z Tensorflow Preprocessing Adapter

Allows use of Tensorflow preprocessing pipeline in PyTorch Transform

Copyright of original Tensorflow code below.

Hacked together by / Copyright 2020 Ross Wightman
    N       皙?      ?gHzG?g?      ?d   c              
   C   s   t |d| |g t j| }t jj||||||dd}|\}	}
}t |	\}}}t |
\}}}t ||||g}t jj| |dd}|W  d   S 1 s0    Y  dS )a  Generates cropped_image using one of the bboxes randomly distorted.

    See `tf.image.sample_distorted_bounding_box` for more documentation.

    Args:
      image_bytes: `Tensor` of binary image data.
      bbox: `Tensor` of bounding boxes arranged `[1, num_boxes, coords]`
          where each coordinate is [0, 1) and the coordinates are arranged
          as `[ymin, xmin, ymax, xmax]`. If num_boxes is 0 then use the whole
          image.
      min_object_covered: An optional `float`. Defaults to `0.1`. The cropped
          area of the image must contain at least this fraction of any bounding
          box supplied.
      aspect_ratio_range: An optional list of `float`s. The cropped area of the
          image must have an aspect ratio = width / height within this range.
      area_range: An optional list of `float`s. The cropped area of the image
          must contain a fraction of the supplied image within in this range.
      max_attempts: An optional `int`. Number of attempts at generating a cropped
          region of the image of the specified constraints. After `max_attempts`
          failures, return the entire image.
      scope: Optional `str` for name scope.
    Returns:
      cropped image `Tensor`
    distorted_bounding_box_cropT)Zbounding_boxesmin_object_coveredaspect_ratio_range
area_rangemax_attemptsZuse_image_if_no_bounding_boxes   ZchannelsN)tfZ
name_scopeimageextract_jpeg_shapesample_distorted_bounding_boxZunstackstackdecode_and_crop_jpeg)image_bytesbboxr   r   r   r   scopeshaper   Z
bbox_beginZ	bbox_size_Zoffset_yZoffset_xZtarget_heightZtarget_widthcrop_windowr    r   c/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/timm/data/tf_preprocessing.pyr
   !   s"    
r
   c                 C   s,   t | |}t |t j}t t ||S )z0At least `x` of `a` and `b` `Tensors` are equal.)r   equalcastint32Zgreater_equalZ
reduce_sum)abxmatchr   r   r   _at_least_x_are_equalU   s    r&   c              	      sv   t jg dt jg dd}t|dddddd	 t j}t|t  d
}t |fdd fdd  S )z!Make a random crop of image_size.)        r'   r   r   )   r(      )dtyper   r   )r   gUUUUUU?)g{Gz?r   
   N)r   r   r   r   r   r   c                      s
   t  S )N)_decode_and_center_cropr   )r   
image_sizer   r   <lambda>l       z)_decode_and_random_crop.<locals>.<lambda>c                      s   t j ggd S Nr   )r   r   resizer   )r   r-   resize_methodr   r   r.   m   r/   )	r   Zconstantfloat32r
   r   r   r&   r   Zcond)r   r-   r2   r   Zoriginal_shapebadr   )r   r   r-   r2   r   _decode_and_random_crop\   s$    r5   c              	   C   s   t j| }|d }|d }t ||t  t t ||t j t j}|| d d }|| d d }t ||||g}	t jj	| |	dd}
t j
|
g||g|d }
|
S )z=Crops to center of image with padding then scales image_size.r   r(      r   r   )r   r   r   r    CROP_PADDINGZminimumr3   r!   r   r   r1   )r   r-   r2   r   Zimage_heightZimage_widthZpadded_center_crop_sizeZoffset_heightoffset_widthr   r   r   r   r   r,   r   s"    
r,   c                 C   s   t j| } | S )zRandom horizontal image flip.)r   r   Zrandom_flip_left_right)r   r   r   r   _flip   s    r9   bicubicc                 C   sb   |dkrt jjjnt jjj}t| ||}t|}t |||dg}t jj||rTt j	nt j
d}|S aA  Preprocesses the given image for evaluation.

    Args:
      image_bytes: `Tensor` representing an image binary of arbitrary size.
      use_bfloat16: `bool` for whether to use bfloat16.
      image_size: image size.
      interpolation: image interpolation method

    Returns:
      A preprocessed image `Tensor`.
    r:   r   )r*   )r   r   ResizeMethodBICUBICBILINEARr5   r9   reshapeconvert_image_dtypebfloat16r3   r   use_bfloat16r-   interpolationr2   r   r   r   r   preprocess_for_train   s    rE   c                 C   sZ   |dkrt jjjnt jjj}t| ||}t |||dg}t jj||rLt jnt j	d}|S r;   )
r   r   r<   r=   r>   r,   r?   r@   rA   r3   rB   r   r   r   preprocess_for_eval   s    rF   Fc                 C   s$   |rt | |||S t| |||S dS )a  Preprocesses the given image.

    Args:
      image_bytes: `Tensor` representing an image binary of arbitrary size.
      is_training: `bool` for whether the preprocessing is for training.
      use_bfloat16: `bool` for whether to use bfloat16.
      image_size: image size.
      interpolation: image interpolation method

    Returns:
      A preprocessed image `Tensor` with value range of [0, 255].
    N)rE   rF   )r   is_trainingrC   r-   rD   r   r   r   preprocess_image   s    rH   c                   @   s&   e Zd ZdddZdd Zdd	 Zd
S )TfPreprocessTransformFr   r:   c                 C   s>   || _ t|tr|d n|| _|| _d | _|  | _d | _d S r0   )	rG   
isinstancetuplesizerD   _image_bytes_build_tf_graphprocess_imagesess)selfrG   rL   rD   r   r   r   __init__   s    
zTfPreprocessTransform.__init__c                 C   sX   t d: t jg t jd| _t| j| jd| j| j}W d    n1 sJ0    Y  |S )Nz/cpu:0)r   r*   F)	r   ZdeviceplaceholderstringrM   rH   rG   rL   rD   )rQ   imgr   r   r   rN      s    "z%TfPreprocessTransform._build_tf_graphc                 C   sl   | j d u rt | _ | j j| j| j|id}| ddt	j
}|jdk r\t	j|dd}t	|d}|S )N)Z	feed_dictr      r   )Zaxisr6   )rP   r   SessionrunrO   rM   roundZclipZastypenpZuint8ndimZexpand_dimsZrollaxis)rQ   r   rU   r   r   r   __call__   s    


zTfPreprocessTransform.__call__N)Fr   r:   )__name__
__module____qualname__rR   rN   r]   r   r   r   r   rI      s   

rI   )r   r   r   r	   N)__doc__Ztensorflow.compat.v1compatZv1r   numpyr[   Z
IMAGE_SIZEr7   Zdisable_eager_executionr
   r&   r5   r,   r9   rE   rF   rH   rI   r   r   r   r   <module>   s.        
4
