
    bi                        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	Z
d dlZd dlmc mZ d dl
mZmZmZ ddlmZmZ ddlmZmZmZ ee
j                   j                   ej4                  ej6                  ee
j                   j                      eej4                     eej6                     f   ZeZdefdZd	 Z  G d
 de      Z! G d de!      Z" G d de!      Z# G d de!      Z$y)    N)ListOptionalTupleUnion)ImageImageFilterImageOps   )ConfigMixinregister_to_config)CONFIG_NAMEPIL_INTERPOLATION	deprecatereturnc                     t        | t        j                  j                        xs: t        | t        j                  t
        j                  f      xr | j                  dv S )a  
    Checks if the input is a valid image.

    A valid image can be:
    - A `PIL.Image.Image`.
    - A 2D or 3D `np.ndarray` or `torch.Tensor` (grayscale or color image).

    Args:
        image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
            The image to validate. It can be a PIL image, a NumPy array, or a torch tensor.

    Returns:
        `bool`:
            `True` if the input is a valid image, `False` otherwise.
    )      )
isinstancePILr   npndarraytorchTensorndimimages    T/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/image_processor.pyis_valid_imager   )   sG      eSYY__-wEBJJPUP\P\C]1^1wchcmcmqwcww    c                     t        | t        j                  t        j                  f      r| j
                  dk(  ryt        |       ryt        | t              rt        d | D              S y)a  
    Checks if the input is a valid image or list of images.

    The input can be one of the following formats:
    - A 4D tensor or numpy array (batch of images).
    - A valid single image: `PIL.Image.Image`, 2D `np.ndarray` or `torch.Tensor` (grayscale image), 3D `np.ndarray` or
      `torch.Tensor`.
    - A list of valid images.

    Args:
        images (`Union[np.ndarray, torch.Tensor, PIL.Image.Image, List]`):
            The image(s) to check. Can be a batch of images (4D tensor/array), a single image, or a list of valid
            images.

    Returns:
        `bool`:
            `True` if the input is valid, `False` otherwise.
       Tc              3   2   K   | ]  }t        |        y wN)r   ).0r   s     r   	<genexpr>z+is_valid_image_imagelist.<locals>.<genexpr>T   s     =U>%(=   F)	r   r   r   r   r   r   r   listallimagess    r   is_valid_image_imagelistr+   <   sR    & &2::u||45&++:J			FD	!=f===r   c                   	    e Zd ZdZeZe	 	 	 	 	 	 	 	 	 d-dededede	dededed	ed
ef fd       Z
edej                  deej                   j                      fd       Zedeeej                   j                      ej                   j                   f   dej                  fd       Zedej                  dej*                  fd       Zedej*                  dej                  fd       Zedeej                  ej*                  f   deej                  ej*                  f   fd       Zedeej                  ej*                  f   deej                  ej*                  f   fd       Zedej                   j                   dej                   j                   fd       Zedej                   j                   dej                   j                   fd       Zed.dej                   j                   dedej                   j                   fd       Zed/dej                   j                   dedefd       Zdej                   j                   dededej                   j                   fdZdej                   j                   dededej                   j                   fdZ	 d0deej                   j                   ej                  ej*                  f   dedede	deej                   j                   ej                  ej*                  f   f
d Z dej                   j                   dej                   j                   fd!Z!	 d1dej*                  d"e"ee      dej*                  fd#Z#	 	 d2deej                   j                   ej                  ej*                  f   de"e   de"e   de$eef   fd$Z%	 	 	 	 d3de&de"e   de"e   de	d%e"e$eeeef      dej*                  fd&Z'	 	 d4dej*                  d'e	d"e"ee      deej                   j                   ej                  ej*                  f   fd(Z(	 d1d)ej                   j                   d*ej                   j                   dej                   j                   d+e"e$eeeef      dej                   j                   f
d,Z) xZ*S )5VaeImageProcessorai  
    Image processor for VAE.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image to [-1,1].
        do_binarize (`bool`, *optional*, defaults to `False`):
            Whether to binarize the image to 0/1.
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
        do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to grayscale format.
    	do_resizevae_scale_factorvae_latent_channelsresamplereducing_gapdo_normalizedo_binarizedo_convert_rgbdo_convert_grayscalec
                 D    t         
|           |r|	rt        dd      y y )Nz`do_convert_rgb` and `do_convert_grayscale` can not both be set to `True`, if you intended to convert the image into RGB format, please set `do_convert_grayscale = False`.z` if you intended to convert the image into grayscale format, please set `do_convert_rgb = False`)super__init__
ValueError)selfr.   r/   r0   r1   r2   r3   r4   r5   r6   	__class__s             r   r9   zVaeImageProcessor.__init__p   s3     	2tr  3>r   r*   r   c                 V   | j                   dk(  r| d   } | dz  j                         j                  d      } | j                  d   dk(  r4| D cg c]'  }t	        j
                  |j                         d      ) }}|S | D cg c]  }t	        j
                  |       }}|S c c}w c c}w )	a  
        Convert a numpy image or a batch of images to a PIL image.

        Args:
            images (`np.ndarray`):
                The image array to convert to PIL format.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images.
        r   N.   uint8r
   Lmoder   roundastypeshaper   	fromarraysqueezer*   r   
pil_imagess      r   numpy_to_pilzVaeImageProcessor.numpy_to_pil   s     ;;!I&F3,%%'..w7<<q RXY%//%--/DYJY  ?EEU%//%0EJE	 ZEs   ,B!B&c                     t        | t              s| g} | D cg c]7  }t        j                  |      j	                  t        j
                        dz  9 } }t        j                  | d      } | S c c}w )aT  
        Convert a PIL image or a list of PIL images to NumPy arrays.

        Args:
            images (`PIL.Image.Image` or `List[PIL.Image.Image]`):
                The PIL image or list of images to convert to NumPy format.

        Returns:
            `np.ndarray`:
                A NumPy array representation of the images.
        g     o@r   axisr   r'   r   arrayrG   float32stackr*   r   s     r   pil_to_numpyzVaeImageProcessor.pil_to_numpy   s_     &$'XFJPQ"((5/((4u<QQ&q) R   <A/c                 |    | j                   dk(  r| d   } t        j                  | j                  dddd            } | S )a  
        Convert a NumPy image to a PyTorch tensor.

        Args:
            images (`np.ndarray`):
                The NumPy image array to convert to PyTorch format.

        Returns:
            `torch.Tensor`:
                A PyTorch tensor representation of the images.
        r   ).Nr   r
   r   )r   r   
from_numpy	transposer)   s    r   numpy_to_ptzVaeImageProcessor.numpy_to_pt   s@     ;;!I&F!!&"2"21aA">?r   c                     | j                         j                  dddd      j                         j                         } | S )a  
        Convert a PyTorch tensor to a NumPy image.

        Args:
            images (`torch.Tensor`):
                The PyTorch tensor to convert to NumPy format.

        Returns:
            `np.ndarray`:
                A NumPy array representation of the images.
        r   r   r   r
   )cpupermutefloatnumpyr)   s    r   pt_to_numpyzVaeImageProcessor.pt_to_numpy   s7     %%aAq1779??Ar   c                     d| z  dz
  S )a  
        Normalize an image array to [-1,1].

        Args:
            images (`np.ndarray` or `torch.Tensor`):
                The image array to normalize.

        Returns:
            `np.ndarray` or `torch.Tensor`:
                The normalized image array.
        g       @g      ? r)   s    r   	normalizezVaeImageProcessor.normalize   s     V|c!!r   c                 2    | dz  dz   j                  dd      S )a  
        Denormalize an image array to [0,1].

        Args:
            images (`np.ndarray` or `torch.Tensor`):
                The image array to denormalize.

        Returns:
            `np.ndarray` or `torch.Tensor`:
                The denormalized image array.
              ?r   r
   )clampr)   s    r   denormalizezVaeImageProcessor.denormalize   s      s"))!Q//r   r   c                 (    | j                  d      } | S )z
        Converts a PIL image to RGB format.

        Args:
            image (`PIL.Image.Image`):
                The PIL image to convert to RGB.

        Returns:
            `PIL.Image.Image`:
                The RGB-converted PIL image.
        RGBconvertr   s    r   convert_to_rgbz VaeImageProcessor.convert_to_rgb   s     e$r   c                 (    | j                  d      } | S )z
        Converts a given PIL image to grayscale.

        Args:
            image (`PIL.Image.Image`):
                The input image to convert.

        Returns:
            `PIL.Image.Image`:
                The image converted to grayscale.
        rB   rk   r   s    r   convert_to_grayscalez&VaeImageProcessor.convert_to_grayscale  s     c"r   blur_factorc                 N    | j                  t        j                  |            } | S )a  
        Applies Gaussian blur to an image.

        Args:
            image (`PIL.Image.Image`):
                The PIL image to convert to grayscale.

        Returns:
            `PIL.Image.Image`:
                The grayscale-converted PIL image.
        )filterr   GaussianBlur)r   rp   s     r   blurzVaeImageProcessor.blur  s"     [55kBCr   
mask_imagewidthheightc           	         | j                  d      } t        j                  |       }|j                  \  }}d}t	        |      D ]#  }|dd|f   dk(  j                         s n|dz  }% d}	t        t	        |            D ]#  }|dd|f   dk(  j                         s n|	dz  }	% d}
t	        |      D ]  }||   dk(  j                         s n|
dz  }
! d}t        t	        |            D ]  }||   dk(  j                         s n|dz  }! t        t        ||z
  d            t        t        |
|z
  d            t        t        ||	z
  |z   |            t        t        ||z
  |z   |            f\  }}}}||z
  ||z
  z  }||z  }||kD  r||z
  |z  }t        |||z
  z
        }||dz  z  }|||dz  z
  z  }|| j                  k\  r|| j                  z
  }||z  }||z  }|dk  r
||z  }||z  }|| j                  k\  r| j                  }n~||z
  |z  }t        |||z
  z
        }||dz  z  }|||dz  z
  z  }|| j                  k\  r|| j                  z
  }||z  }||z  }|dk  r
||z  }||z  }|| j                  k\  r| j                  }||||fS )a   
        Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect
        ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for
        processing are 512x512, the region will be expanded to 128x128.

        Args:
            mask_image (PIL.Image.Image): Mask image.
            width (int): Width of the image to be processed.
            height (int): Height of the image to be processed.
            pad (int, optional): Padding to be added to the crop region. Defaults to 0.

        Returns:
            tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and
            matches the original aspect ratio.
        rB   r   Nr
   r   )rl   r   rR   rH   ranger(   reversedintmaxminrw   rv   )ru   rv   rw   padmaskhw	crop_lefti
crop_rightcrop_topcrop_bottomx1y1x2y2ratio_crop_regionratio_processingdesired_heightdesired_height_diffdiffdesired_widthdesired_width_diffs                          r   get_crop_regionz!VaeImageProcessor.get_crop_region%  s   $  '',
xx
# zz1	q 	AAJ!O((*NI	
 
%(# 	AAJ!O((*!OJ	
 q 	AGqL%%'MH	
 %(# 	AGqL%%'1K	 IOQ'(HsNA&'A
NS(!,-AOc)1-.	
BB  "Wb1 6>// 2g)99N"%nR&@"A%**B%(;q(@@@BZ&&&J---d
d
AvbbZ&&&&&"W(88M!$]b2g%>!?$))B$'9Q'>>>BZ%%%J,,,d
d
AvbbZ%%%%%2r2~r   c           	         ||z  }|j                   |j                  z  }||k  r|n|j                   |z  |j                  z  }||k\  r|n|j                  |z  |j                   z  }|j                  ||ft        d         }t	        j
                  d||f      }	|	j                  ||dz  |dz  z
  |dz  |dz  z
  f       ||k  r|dz  |dz  z
  }
|
dkD  rm|	j                  |j                  ||
fdd|df      d       |	j                  |j                  ||
fd|j                  ||j                  f      d|
|z   f       |	S ||kD  r}|dz  |dz  z
  }|dkD  rm|	j                  |j                  ||fddd|f      d       |	j                  |j                  ||f|j                   d|j                   |f      ||z   df       |	S )a*  
        Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
        the image within the dimensions, filling empty with data from image.

        Args:
            image (`PIL.Image.Image`):
                The image to resize and fill.
            width (`int`):
                The width to resize the image to.
            height (`int`):
                The height to resize the image to.

        Returns:
            `PIL.Image.Image`:
                The resized and filled image.
        lanczosr1   rj   r   boxr   )r   r   rv   rw   resizer   r   newpaste)r;   r   rv   rw   ratio	src_ratiosrc_wsrc_hresizedresfill_height
fill_widths               r   _resize_and_fillz"VaeImageProcessor._resize_and_fill  s   . KK%,,.	*f0D0T9,%,,2F%++2U,,u~8I)8T,Uiiv/		'
UaZ 71uPQz9QR	S9 A+
2KQ		'..%)=Aq%QRCS.TZ`	a		NNE;#7aQVX_XfXf=gNhK%/0   
 Y!eqj0JA~		'..*f)=Aq!VCT.U[a	b		NNJ#7gmmQPWP]P]_e=fNg#e+Q/  
 
r   c                    ||z  }|j                   |j                  z  }||kD  r|n|j                   |z  |j                  z  }||k  r|n|j                  |z  |j                   z  }|j                  ||ft        d         }t	        j
                  d||f      }	|	j                  ||dz  |dz  z
  |dz  |dz  z
  f       |	S )a  
        Resize the image to fit within the specified width and height, maintaining the aspect ratio, and then center
        the image within the dimensions, cropping the excess.

        Args:
            image (`PIL.Image.Image`):
                The image to resize and crop.
            width (`int`):
                The width to resize the image to.
            height (`int`):
                The height to resize the image to.

        Returns:
            `PIL.Image.Image`:
                The resized and cropped image.
        r   r   rj   r   r   r   )
r;   r   rv   rw   r   r   r   r   r   r   s
             r   _resize_and_cropz"VaeImageProcessor._resize_and_crop  s    , KK%,,.	*f0D0T9,%,,2F%++2U,,u~8I)8T,Uiiv/		'
UaZ 71uPQz9QR	S
r   resize_modec                 >   |dk7  r2t        |t        j                  j                        st        d|       t        |t        j                  j                        r|dk(  rG|j	                  ||ft
        | j                  j                     | j                  j                        }|S |dk(  r| j                  |||      }|S |dk(  r| j                  |||      }|S t        d| d      t        |t        j                        r/t        j                  j                  j                  |||f      }|S t        |t         j"                        rO| j%                  |      }t        j                  j                  j                  |||f      }| j'                  |      }|S )	a  
        Resize image.

        Args:
            image (`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
                The image input, can be a PIL image, numpy array or pytorch tensor.
            height (`int`):
                The height to resize to.
            width (`int`):
                The width to resize to.
            resize_mode (`str`, *optional*, defaults to `default`):
                The resize mode to use, can be one of `default` or `fill`. If `default`, will resize the image to fit
                within the specified width and height, and it may not maintaining the original aspect ratio. If `fill`,
                will resize the image to fit within the specified width and height, maintaining the aspect ratio, and
                then center the image within the dimensions, filling empty with data from image. If `crop`, will resize
                the image to fit within the specified width and height, maintaining the aspect ratio, and then center
                the image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
                supported for PIL image input.

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
                The resized image.
        defaultz2Only PIL image input is supported for resize_mode )r1   r2   fillcropzresize_mode  is not supported)size)r   r   r   r:   r   r   configr1   r2   r   r   r   r   nn
functionalinterpolater   r   r[   ra   )r;   r   rw   rv   r   s        r   r   zVaeImageProcessor.resize  s   < )#Juciioo,NQR]Q^_``eSYY__-i'FO.t{{/C/CD!%!9!9 % 0 ' &--eUFC$ # &--eUFC   !<}<M!NOOu||,HH''33e_ 4 E  rzz*$$U+EHH''33e_ 4 E $$U+Er   c                 &    d||dk  <   d||dk\  <   |S )a-  
        Create a mask.

        Args:
            image (`PIL.Image.Image`):
                The image input, should be a PIL image.

        Returns:
            `PIL.Image.Image`:
                The binarized image. Values less than 0.5 are set to 0, values greater than 0.5 are set to 1.
        r   rf   r
   rc   )r;   r   s     r   binarizezVaeImageProcessor.binarize  s%     eckeslr   do_denormalizec           	         |)| j                   j                  r| j                  |      S |S t        j                  t        |j                  d         D cg c]   }||   r| j                  ||         n||   " c}      S c c}w )a  
        Denormalize a batch of images based on a condition list.

        Args:
            images (`torch.Tensor`):
                The input image tensor.
            do_denormalize (`Optional[List[bool]`, *optional*, defaults to `None`):
                A list of booleans indicating whether to denormalize each image in the batch. If `None`, will use the
                value of `do_normalize` in the `VaeImageProcessor` config.
        r   )r   r3   rh   r   rT   ry   rH   )r;   r*   r   r   s       r   _denormalize_conditionallyz,VaeImageProcessor._denormalize_conditionally!  s     !/3{{/G/G4##F+SVS{{V[\b\h\hij\kVlmQRN1,=TfQi(6!9Lm
 	
ms   %Bc                     |jt        |t        j                  j                        r|j                  }n9t        |t        j
                        r|j                  d   }n|j                  d   }|jt        |t        j                  j                        r|j                  }n9t        |t        j
                        r|j                  d   }n|j                  d   } fd||fD        \  }}||fS )a3  
        Returns the height and width of the image, downscaled to the next integer multiple of `vae_scale_factor`.

        Args:
            image (`Union[PIL.Image.Image, np.ndarray, torch.Tensor]`):
                The image input, which can be a PIL image, NumPy array, or PyTorch tensor. If it is a NumPy array, it
                should have shape `[batch, height, width]` or `[batch, height, width, channels]`. If it is a PyTorch
                tensor, it should have shape `[batch, channels, height, width]`.
            height (`Optional[int]`, *optional*, defaults to `None`):
                The height of the preprocessed image. If `None`, the height of the `image` input will be used.
            width (`Optional[int]`, *optional*, defaults to `None`):
                The width of the preprocessed image. If `None`, the width of the `image` input will be used.

        Returns:
            `Tuple[int, int]`:
                A tuple containing the height and width, both resized to the nearest integer multiple of
                `vae_scale_factor`.
        r   r
   r   c              3   V   K   | ]   }||j                   j                  z  z
   " y wr#   )r   r/   )r$   xr;   s     r   r%   z=VaeImageProcessor.get_default_height_width.<locals>.<genexpr>^  s*      
56ADKK0000
s   &))r   r   r   rw   r   r   rH   rv   )r;   r   rw   rv   s   `   r   get_default_height_widthz*VaeImageProcessor.get_default_height_width5  s    2 >%1E5<<0QQ=%1E5<<0AA
;@&/
v u}r   crops_coordsc           	      D   t         j                  j                  t        j                  t        j
                  f}| j                  j                  rt        |t        j
                  t        j                  f      r||j                  dk(  rmt        |t        j
                        r|j                  d      }nA|j                  d   dk(  rt        j                  |d      }nt        j                  |d      }t        |t              r`t        |d   t        j                        rC|d   j                  dk(  r1t        j                  dt                t        j"                  |d      }t        |t              r`t        |d   t        j
                        rC|d   j                  dk(  r1t        j                  dt                t	        j$                  |d      }t'        |      s$t)        d	d
j+                  d |D                     t        |t              s|g}t        |d   t         j                  j                        r||D cg c]  }|j-                  |       }}| j                  j.                  r;| j1                  |d   ||      \  }}|D cg c]  }| j3                  ||||       }}| j                  j4                  r|D cg c]  }| j7                  |       }}n4| j                  j                  r|D cg c]  }| j9                  |       }}| j;                  |      }| j=                  |      }nt        |d   t        j                        r|d   j                  dk(  rt        j"                  |d      nt        j>                  |d      }| j=                  |      }| j1                  |||      \  }}| j                  j.                  r| j3                  |||      }nt        |d   t        j
                        r|d   j                  dk(  rt	        j$                  |d      nt	        j>                  |d      }| j                  j                  r |j                  dk(  r|j                  d      }|j                  d   }|| j                  j@                  k(  r|S | j1                  |||      \  }}| j                  j.                  r| j3                  |||      }| j                  jB                  }	|	rR|jE                         dk  r?t        j                  d|jE                          d|jG                          dt                d}	|	r| jI                  |      }| j                  jJ                  r| jM                  |      }|S c c}w c c}w c c}w c c}w )a  
        Preprocess the image input.

        Args:
            image (`PipelineImageInput`):
                The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
                supported formats.
            height (`int`, *optional*):
                The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default
                height.
            width (`int`, *optional*):
                The width in preprocessed. If `None`, will use get_default_height_width()` to get the default width.
            resize_mode (`str`, *optional*, defaults to `default`):
                The resize mode, can be one of `default` or `fill`. If `default`, will resize the image to fit within
                the specified width and height, and it may not maintaining the original aspect ratio. If `fill`, will
                resize the image to fit within the specified width and height, maintaining the aspect ratio, and then
                center the image within the dimensions, filling empty with data from image. If `crop`, will resize the
                image to fit within the specified width and height, maintaining the aspect ratio, and then center the
                image within the dimensions, cropping the excess. Note that resize_mode `fill` and `crop` are only
                supported for PIL image input.
            crops_coords (`List[Tuple[int, int, int, int]]`, *optional*, defaults to `None`):
                The crop coordinates for each image in the batch. If `None`, will not crop the image.

        Returns:
            `torch.Tensor`:
                The preprocessed image.
        r   r
   rA   r   rO   r!   zPassing `image` as a list of 4d np.ndarray is deprecated.Please concatenate the list along the batch dimension and pass it as a single 4d np.ndarrayzPassing `image` as a list of 4d torch.Tensor is deprecated.Please concatenate the list along the batch dimension and pass it as a single 4d torch.Tensorz9Input is in incorrect format. Currently, we only support , c              3   2   K   | ]  }t        |        y wr#   )str)r$   r   s     r   r%   z/VaeImageProcessor.preprocess.<locals>.<genexpr>  s     UxabVYZ[V\Uxr&   )r   Passing `image` as torch tensor with value range in [-1,1] is deprecated. The expected value range for image tensor is [0,1] when passing as pytorch tensor or numpy Array. You passed `image` with value range [,]F)'r   r   r   r   r   r   r   r6   r   r   	unsqueezerH   expand_dimsr'   warningswarnFutureWarningconcatenatecatr+   r:   joinr   r.   r   r   r5   rm   ro   rV   r[   rT   r0   r3   r}   r|   rd   r4   r   )
r;   r   rw   rv   r   r   supported_formatsr   channelr3   s
             r   
preprocesszVaeImageProcessor.preprocessd  s   F !YY__bjj%,,G ;;++
55<<QSQ[Q[B\0]bgblblpqbq%. *
 ;;r?a'NN5q9ENN5r:EeT"z%(BJJ'GERSHMM]^L^MMn
 NN5q1EeT"z%(ELL'IeTUhmm_`N`MMp
 IIe!,E'.KDIIUxfwUxLxKyz  %&GEeAh		0'7<=!-=={{$$ $ = =eAhPU VY^_TUQ;O__{{))9>?A,,Q/??11?DE!2215EE%%e,E$$U+Ea"**-5:1X]]a5GBNN5q1RXXV[bcMdE$$U+E 99%OMFE{{$$E659a%,,/05a0BEIIe!,TY`aHbE{{//EJJ!O*kk!nG$++999 99%OMFE{{$$E659 {{//EIIK!OMMgglgpgpgrfsstuzu~u~  vA  uB  BCD
 !LNN5)E;;""MM%(Ee > `?Es   VV
V?Voutput_typec                 :   t        |t        j                        st        dt	        |       d      |dvrd| d}t        dd|d	       d
}|dk(  r|S | j                  ||      }|dk(  r|S | j                  |      }|d
k(  r|S |dk(  r| j                  |      S y)  
        Postprocess the image output from tensor to `output_type`.

        Args:
            image (`torch.Tensor`):
                The image input, should be a pytorch tensor with shape `B x C x H x W`.
            output_type (`str`, *optional*, defaults to `pil`):
                The output type of the image, can be one of `pil`, `np`, `pt`, `latent`.
            do_denormalize (`List[bool]`, *optional*, defaults to `None`):
                Whether to denormalize the image to [0,1]. If `None`, will use the value of `do_normalize` in the
                `VaeImageProcessor` config.

        Returns:
            `PIL.Image.Image`, `np.ndarray` or `torch.Tensor`:
                The postprocessed image.
        1Input for postprocessing is in incorrect format:  . We only support pytorch tensorlatentptr   pilthe output_type v is outdated and has been set to `np`. Please make sure to set it to one of these instead: `pil`, `np`, `pt`, `latent`Unsupported output_type1.0.0Fstandard_warnr   r   r   r   N)	r   r   r   r:   typer   r   ra   rM   )r;   r   r   r   deprecation_messages        r   postprocesszVaeImageProcessor.postprocess  s    , %.CDK=Ppq  ;;";- 0. .   /:M]bcK("L//~F$L  '$L%$$U++  r   r   
init_imagecrop_coordsc                    |j                   |j                  }}t        j                  j	                  d||f      }|j                  |j                  d      j                  d      t        j                  |j                  d                   |j                  d      }|m|\  }}	}
}|
|z
  }||	z
  }t        j                  j	                  d||f      }| j                  |||d      }|j                  |||	f       |j                  d      }|j                  d      }|j                  |       |j                  d      }|S )a  
        Applies an overlay of the mask and the inpainted image on the original image.

        Args:
            mask (`PIL.Image.Image`):
                The mask image that highlights regions to overlay.
            init_image (`PIL.Image.Image`):
                The original image to which the overlay is applied.
            image (`PIL.Image.Image`):
                The image to overlay onto the original.
            crop_coords (`Tuple[int, int, int, int]`, *optional*):
                Coordinates to crop the image. If provided, the image will be cropped accordingly.

        Returns:
            `PIL.Image.Image`:
                The final image with the overlay applied.
        RGBaRGBArB   )r   r   )rw   rv   r   rj   )rv   rw   r   r   r   r   rl   r	   invertr   alpha_composite)r;   r   r   r   r   rv   rw   init_image_maskedr   yr   r   r   r   
base_images                  r   apply_overlayzVaeImageProcessor.apply_overlay  s,   2 #((**;*;vIIMM&5&/B
 2 26 : B B6 JQYQ`Q`aeamamnqarQst-55f="&LAq"bQAQAvv?JKKaqfKMEUQF+&&u-Ef%/0e$r   )	T   r!   r   NTFFF)r!   )r   )r   r#   )NN)NNr   Nr   N)+__name__
__module____qualname____doc__r   config_namer   boolr{   r   r9   staticmethodr   r   r   r   r   rM   r   rV   r   r   r[   ra   rd   rh   rm   ro   rt   r   r   r   r   r   r   r   r   r   PipelineImageInputr   r   r   __classcell__r<   s   @r   r-   r-   X   s   * K  !#$! !!$%*  !	
      # ( RZZ D,A  . U4		#8#))//#IJ rzz  & BJJ 5<<  $ ELL RZZ   "%

ELL 89 "eBJJPUP\P\D\>] " " 0E"**ell":; 0bjjRWR^R^F^@_ 0 0 ciioo #))//    CIIOO 		    CIIOO # ciioo    WCIIOO WC W W Wr2yy2 2 	2
 
2hyy  	
 
L %:SYY__bjj%,,>?: : 	:
 : 
syy

ELL8	9:xciioo #))// $ LP
ll
4<T$Z4H
	
. !%#	-SYY__bjj%,,>?- - }	-
 
sCx-d !%#$<@A!A A }	A
 A uS#sC%789A 
AL !/3	0,||0, 0, !d,	0,
 
syy

ELL8	90,n <@-iioo- IIOO- yy	-
 eCc3$678- 
-r   r-   c                       e Zd ZdZeZe	 	 	 	 ddedede	def fd       Z
edej                  deej                   j                      fd	       Zedeeej                   j                      ej                   j                   f   dej                  fd
       Zedeej                  ej*                  f   deej                  ej*                  f   fd       Zdej                  deej                   j                      fdZ	 	 ddej*                  de	deee      deej                   j                   ej                  ej*                  f   fdZ	 	 	 ddeej*                  ej                   j                   ej                  f   deej*                  ej                   j                   ej                  f   dee   dee   dee   dej*                  fdZ xZS )VaeImageProcessorLDM3Da  
    Image processor for VAE LDM3D.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image to [-1,1].
    r.   r/   r1   r3   c                 "    t         |           y r#   r8   r9   )r;   r.   r/   r1   r3   r<   s        r   r9   zVaeImageProcessorLDM3D.__init__Z  s     	r   r*   r   c           
      n   | j                   dk(  r| d   } | dz  j                         j                  d      } | j                  d   dk(  r4| D cg c]'  }t	        j
                  |j                         d      ) }}|S | D cg c]#  }t	        j
                  |d	d	d	d	d	df         % }}|S c c}w c c}w )
ab  
        Convert a NumPy image or a batch of images to a list of PIL images.

        Args:
            images (`np.ndarray`):
                The input NumPy array of images, which can be a single image or a batch.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images converted from the input NumPy array.
        r   r>   r?   r@   rA   r
   rB   rC   NrE   rK   s      r   rM   z#VaeImageProcessorLDM3D.numpy_to_pild  s     ;;!I&F3,%%'..w7<<q RXY%//%--/DYJY  IOOu%//%1bqb/:OJO	 ZOs   ,B-(B2c                     t        | t              s| g} | D cg c]7  }t        j                  |      j	                  t        j
                        dz  9 } }t        j                  | d      } | S c c}w )aI  
        Convert a PIL image or a list of PIL images to NumPy arrays.

        Args:
            images (`Union[List[PIL.Image.Image], PIL.Image.Image]`):
                The input image or list of images to be converted.

        Returns:
            `np.ndarray`:
                A NumPy array of the converted images.
        i  r   rO   rQ   rU   s     r   depth_pil_to_numpyz)VaeImageProcessorLDM3D.depth_pil_to_numpy|  s_     &$'XFPVWu"((5/((4	BWW&q) XrW   r   c                 :    | dddddf   dz  | dddddf   z   S )a*  
        Convert an RGB-like depth image to a depth map.

        Args:
            image (`Union[np.ndarray, torch.Tensor]`):
                The RGB-like depth image to convert.

        Returns:
            `Union[np.ndarray, torch.Tensor]`:
                The corresponding depth map.
        Nr
      r   rc   r   s    r   rgblike_to_depthmapz*VaeImageProcessorLDM3D.rgblike_to_depthmap  s(     Q1W~$uQ1W~55r   c                    |j                   dk(  r|d   }|ddddddddf   }|j                  d   dk(  rW|dz  j                         j                  d      }|D cg c](  }t	        j
                  | j                  |      d	      * }}|S |j                  d   d
k(  rH|dz  j                  t        j                        }|D cg c]  }t	        j
                  |d	       }}|S t        d      c c}w c c}w )au  
        Convert a NumPy depth image or a batch of images to a list of PIL images.

        Args:
            images (`np.ndarray`):
                The input NumPy array of depth images, which can be a single image or a batch.

        Returns:
            `List[PIL.Image.Image]`:
                A list of PIL images converted from the input NumPy depth images.
        r   r>   NrA      r?   r@   zI;16rC   r!   g    @zNot supported)
r   rH   rF   rG   r   rI   r   r   uint16	Exception)r;   r*   images_depthimage_depthrL   s        r   numpy_to_depthz%VaeImageProcessorLDM3D.numpy_to_depth  s     ;;!I&FaAqrk*<<q (3.557>>wGLgsXc 8 8 EFSJ   \\""(72::299ELWcd%//+FCdJd  O,,
 es   -C4C9r   r   c                 P   t        |t        j                        st        dt	        |       d      |dvrd| d}t        dd|d	       d
}| j                  ||      }| j                  |      }|d
k(  rw|j                  d   dk(  rAt        j                  |D cg c]  }| j                  |ddddddf         ! c}d      }n|ddddddddf   }|ddddddddf   |fS |dk(  r"| j                  |      | j                  |      fS t        d| d      c c}w )r   r   r   r   r   r   r   r   Fr   r   rA   r  Nr   r   rO   r   z
This type r   )r   r   r   r:   r   r   r   ra   rH   r   rT   r   rM   r  r  )r;   r   r   r   r   imr  s          r   r   z"VaeImageProcessorLDM3D.postprocess  sL   , %.CDK=Ppq  ;;";- 0. .   /:M]bcK//~F  '${{2!# hhY^'_SU(@(@Aq!"H(N'_fgh#Aq!QRK0Aq"1"%{22%$$U+T-@-@-GGGj5FGHH (`s   $D#rgbdepthrw   rv   
target_resc           	         t         j                  j                  t        j                  t        j
                  f| j                  j                  rDt        |t        j
                  t        j                  f      r|j                  dk(  rt        d      t        |      r|g}|g}n[t        |t              rt        fd|D              s7t        d|D cg c]  }t        |       c} ddj                               t        |d   t         j                  j                        r| j                  j                   rt        d      | j                  j"                  s|r]|s| j%                  |d   ||      n|\  }}|D cg c]  }| j'                  |||       }}|D cg c]  }| j'                  |||       }}| j)                  |      }| j+                  |      }| j-                  |      }| j+                  |      }ngt        |d   t        j                        r!|d   j                  dk(  rt        j.                  |d	      nt        j0                  |d	      }| j+                  |      }| j%                  |||      \  }}| j                  j"                  r| j'                  |||      }|d   j                  dk(  rt        j.                  |d	      nt        j0                  |d	      }| j+                  |      }| j%                  |||      \  }}| j                  j"                  r<| j'                  |||      }n(t        |d   t        j
                        rt        d      | j                  j2                  }|j5                         dk  rA|r?t7        j8                  d
|j5                          d|j;                          dt<               d}|r"| j?                  |      }| j?                  |      }| j                  j@                  r"| jC                  |      }| jC                  |      }||fS c c}w c c}w c c}w )a`  
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays, or PyTorch tensors.

        Args:
            rgb (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
                The RGB input image, which can be a single image or a batch.
            depth (`Union[torch.Tensor, PIL.Image.Image, np.ndarray]`):
                The depth input image, which can be a single image or a batch.
            height (`Optional[int]`, *optional*, defaults to `None`):
                The desired height of the processed image. If `None`, defaults to the height of the input image.
            width (`Optional[int]`, *optional*, defaults to `None`):
                The desired width of the processed image. If `None`, defaults to the width of the input image.
            target_res (`Optional[int]`, *optional*, defaults to `None`):
                Target resolution for resizing the images. If specified, overrides height and width.

        Returns:
            `Tuple[torch.Tensor, torch.Tensor]`:
                A tuple containing the processed RGB and depth images as PyTorch tensors.
        r   zThis is not yet supportedc              3   6   K   | ]  }t        |        y wr#   )r   )r$   r   r   s     r   r%   z4VaeImageProcessorLDM3D.preprocess.<locals>.<genexpr>  s     /^UV
1>O0P/^s   zInput is in incorrect format: z. Currently, we only support r   r   r!   rO   r   r   r   F)"r   r   r   r   r   r   r   r6   r   r   r  r'   r(   r:   r   r   r5   r.   r   r   rV   r[   r   r   rT   r3   r}   r   r   r|   r   rd   r4   r   )	r;   r
  r  rw   rv   r  r   r3   r   s	           @r   r   z!VaeImageProcessorLDM3D.preprocess  s   6 !YY__bjj%,,G ;;++
3rzz@Z0[`c`h`hlm`m788c,-%CGES$'C/^Z]/^,^031Ga$q'1G0HHefjfofo  qB  gC  fD  E  c!fciioo.{{)) ;<< {{$$
\f = =c!ffe Tlv>ABt{{1fe4BB@EF1Q6FF##C(C""3'C++E2E$$U+EA

+14Q1A"..1-rxxPSZ[G\C""3'C 99#vuMMFE{{$$kk#vu558V[[A5EBNN5q1288TY`aKbE$$U+E 99%OMFE{{$$E659A-7884 {{//779q=\MMggjgngngpfqqrsvszszs|r}}~@
 !L..%CNN5)E;;""--$CMM%(EEzW 2H CFs   P7
P<$Q)Tr   r   Tr   )NNN)r   r   r   r   r   r   r   r   r{   r   r9   r   r   r   r   r   r   rM   r   r   r   r   r   r  r   r   r   r   r   s   @r   r   r   I  s8    K  !!!  	
   RZZ D,A  . 5ciioo)>		)O#P UWU_U_  & 65U\\)A#B 6uRZZY^YeYeMeGf 6 6RZZ D4I > !/3	0I||0I 0I !d,	0I
 
syy

ELL8	90Il !%#$(q5<<"**<=q U\\399??BJJ>?q 	q
 }q SMq 
qr   r   c                        e Zd ZdZeZe	 	 	 	 	 	 ddedede	dededef fd       Z
ed	ej                  d
ededefd       Z xZS )IPAdapterMaskProcessora  
    Image processor for IP Adapter image masks.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `False`):
            Whether to normalize the image to [-1,1].
        do_binarize (`bool`, *optional*, defaults to `True`):
            Whether to binarize the image to 0/1.
        do_convert_grayscale (`bool`, *optional*, defaults to be `True`):
            Whether to convert the images to grayscale format.

    r.   r/   r1   r3   r4   r6   c                 0    t         |   ||||||       y N)r.   r/   r1   r3   r4   r6   r   r;   r.   r/   r1   r3   r4   r6   r<   s          r   r9   zIPAdapterMaskProcessor.__init__w  )     	-%#!5 	 	
r   r   
batch_sizenum_queriesvalue_embed_dimc                 H   | j                   d   }| j                   d   }||z  }t        t        j                  ||z              }t        |      t        |t        |      z  dk7        z   }||z  }t	        j
                  | j                  d      ||fd      j                  d      }	|	j                   d   |k  r|	j                  |dd      }	|	j                  |	j                   d   d      }	||z  }
|
|k  rDt        j                  dt               t	        j                  |	d||	j                   d   z
  fd	      }	|
|kD  r%t        j                  dt               |	d
d
d
|f   }	|	j                  |	j                   d   |	j                   d   d      j                  dd|      }	|	S )a  
        Downsamples the provided mask tensor to match the expected dimensions for scaled dot-product attention. If the
        aspect ratio of the mask does not match the aspect ratio of the output image, a warning is issued.

        Args:
            mask (`torch.Tensor`):
                The input mask tensor generated with `IPAdapterMaskProcessor.preprocess()`.
            batch_size (`int`):
                The batch size.
            num_queries (`int`):
                The number of queries.
            value_embed_dim (`int`):
                The dimensionality of the value embeddings.

        Returns:
            `torch.Tensor`:
                The downsampled mask tensor.

        r
   r   r   bicubic)r   rD   rA   zThe aspect ratio of the mask does not match the aspect ratio of the output image. Please update your masks or adjust the output size for optimal performance.g        )valueN)rH   r{   mathsqrtFr   r   rJ   repeatviewr   r   UserWarningr~   )r   r  r  r  o_ho_wr   mask_hmask_wmask_downsampledownsampled_areas              r   
downsamplez!IPAdapterMaskProcessor.downsample  s   * jjmjjmc	TYY{U234VsK#f+$=!#CDD&--q(9@PW`aiijkl   #j0-44ZAFO)../D/DQ/GL!F? k)MM^
  eeOaG\G\]^G_9_5`hklOk)MM^
 .a+o>O *../D/DQ/GI^I^_`Iacdellq/
 r   )Tr   r   FTT)r   r   r   r   r   r   r   r   r{   r   r9   r   r   r   r'  r   r   s   @r   r  r  a  s    & K  !!" %)

 
 	

 
 
 #
 
$ ; ;3 ;S ;[^ ; ;r   r  c                        e Zd ZdZe	 	 	 	 	 	 ddedededededef fd       Ze	d	ed
ede
deeef   fd       Ze	dej                  dededej                  fd       Z xZS )PixArtImageProcessora  
    Image processor for PixArt image resize and crop.

    Args:
        do_resize (`bool`, *optional*, defaults to `True`):
            Whether to downscale the image's (height, width) dimensions to multiples of `vae_scale_factor`. Can accept
            `height` and `width` arguments from [`image_processor.VaeImageProcessor.preprocess`] method.
        vae_scale_factor (`int`, *optional*, defaults to `8`):
            VAE scale factor. If `do_resize` is `True`, the image is automatically resized to multiples of this factor.
        resample (`str`, *optional*, defaults to `lanczos`):
            Resampling filter to use when resizing the image.
        do_normalize (`bool`, *optional*, defaults to `True`):
            Whether to normalize the image to [-1,1].
        do_binarize (`bool`, *optional*, defaults to `False`):
            Whether to binarize the image to 0/1.
        do_convert_rgb (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to RGB format.
        do_convert_grayscale (`bool`, *optional*, defaults to be `False`):
            Whether to convert the images to grayscale format.
    r.   r/   r1   r3   r4   r6   c                 0    t         |   ||||||       y r  r   r  s          r   r9   zPixArtImageProcessor.__init__  r  r   rw   rv   ratiosr   c                     t        | |z        t        |j                         fd      }||   }t        |d         t        |d         fS )a  
        Returns the binned height and width based on the aspect ratio.

        Args:
            height (`int`): The height of the image.
            width (`int`): The width of the image.
            ratios (`dict`): A dictionary where keys are aspect ratios and values are tuples of (height, width).

        Returns:
            `Tuple[int, int]`: The closest binned height and width.
        c                 2    t        t        |       z
        S r#   )absr_   )r   ars    r   <lambda>z@PixArtImageProcessor.classify_height_width_bin.<locals>.<lambda>   s    SuPRAR=S r   )keyr   r
   )r_   r}   keysr{   )rw   rv   r+  closest_ratio
default_hwr/  s        @r   classify_height_width_binz.PixArtImageProcessor.classify_height_width_bin  sM     6E>"FKKM/STM*
:a=!3z!}#555r   samples	new_width
new_heightc                 >   | j                   d   | j                   d   }}||k7  s||k7  rtt        ||z  ||z        }t        ||z        }t        ||z        }t        j                  | ||fdd      } ||z
  dz  }||z   }	||z
  dz  }
|
|z   }| dddd|
|||	f   } | S )a  
        Resizes and crops a tensor of images to the specified dimensions.

        Args:
            samples (`torch.Tensor`):
                A tensor of shape (N, C, H, W) where N is the batch size, C is the number of channels, H is the height,
                and W is the width.
            new_width (`int`): The desired width of the output images.
            new_height (`int`): The desired height of the output images.

        Returns:
            `torch.Tensor`: A tensor containing the resized and cropped images.
        r   r   bilinearF)r   rD   align_cornersN)rH   r|   r{   r  r   )r6  r7  r8  orig_height
orig_widthr   resized_widthresized_heightstart_xend_xstart_yend_ys               r   resize_and_crop_tensorz+PixArtImageProcessor.resize_and_crop_tensor  s     #*--"2GMM!4DZ *$
i(?
[0)j2HIE
U 23M u!45N mm~}=J^cG
 %y0Q6Gi'E%
2q8Gj(EaGEM75=@AGr   )Tr   r   TFF)r   r   r   r   r   r   r{   r   r9   r   dictr   r5  r   r   rD  r   r   s   @r   r)  r)    s    *   !!!!%*

 
 	

 
 
 #
 
$ 6# 6c 64 6ERUWZRZO 6 6" " " "RU "Z_ZfZf " "r   r)  )%r  r   typingr   r   r   r   r`   r   	PIL.Imager   r   torch.nn.functionalr   r   r  r   r   r	   configuration_utilsr   r   utilsr   r   r   r   r   r   PipelineDepthInputr   r   r+   r-   r   r  r)  rc   r   r   <module>rL     s      / /      , , @ < < IIOOJJ	LL  ( xT x&8n nbU. Upe. eP^, ^r   