
    /;ji                        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j        ej        ee
j        j                 eej                 eej                 f         ZeZd Zd Z G d	 d
e          Z  G d de           Z! G d de           Z" G d de           Z#dS )    N)ListOptionalTupleUnion)ImageImageFilterImageOps   )ConfigMixinregister_to_config)CONFIG_NAMEPIL_INTERPOLATION	deprecatec                     t          | t          j        j                  p.t          | t          j        t
          j        f          o| j        dv S )N)      )
isinstancePILr   npndarraytorchTensorndimimages    S/root/voice-cloning/.venv/lib/python3.11/site-packages/diffusers/image_processor.pyis_valid_imager   )   s?    eSY_--wEBJPUP\C]1^1^1wchcmqwcww    c                     t          | t          j        t          j        f          r| j        dk    rdS t          |           rdS t          | t                    rt          d | D                       S dS )N   Tc              3   4   K   | ]}t          |          V  d S N)r   .0r   s     r   	<genexpr>z+is_valid_image_imagelist.<locals>.<genexpr>8   s*      ==U>%((======r   F)	r   r   r   r   r   r   r   listallimagess    r   is_valid_image_imagelistr*   -   sy     &2:u|455 >&+:J:Jt			 >t	FD	!	! >==f======5r   c                       e Zd ZdZeZe	 	 	 	 	 	 	 	 d4d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d5dej        j        dedej        j        fd            Zed6d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	 d7d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!	 	 d8deej        j        ej        ej        f         d e"e         de"e         de#eef         fd)Z$	 	 	 	 d9de%d e"e         de"e         d%e	d*e"e#eeeef                  de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;d0ej        j        d1ej        j        dej        j        d2e"e#eeeef                  dej        j        f
d3Z( xZ)S )<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.
    T   r    lanczosF	do_resizevae_scale_factorvae_latent_channelsresampledo_normalizedo_binarizedo_convert_rgbdo_convert_grayscalec	                 t    t                                                       |r|rt          dd          d S d S )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/   r0   r1   r2   r3   r4   r5   r6   	__class__s
            r   r9   zVaeImageProcessor.__init__T   sZ     	 	2 	tr  	 	 	 	r   r)   returnc                     | j         dk    r| d         } | dz                                                      d          } | j        d         dk    rd | D             }nd | D             }|S )	zL
        Convert a numpy image or a batch of images to a PIL image.
        r   N.   uint8r
   c                 ^    g | ]*}t          j        |                                d           +S Lmoder   	fromarraysqueezer#   s     r   
<listcomp>z2VaeImageProcessor.numpy_to_pil.<locals>.<listcomp>r   /    YYY%/%--//DDDYYYr   c                 6    g | ]}t          j        |          S  r   rI   r#   s     r   rK   z2VaeImageProcessor.numpy_to_pil.<locals>.<listcomp>t   s"    EEEU%/%00EEEr   r   roundastypeshaper)   
pil_imagess     r   numpy_to_pilzVaeImageProcessor.numpy_to_pilh   s    
 ;!I&F3,%%''..w77<q  YYRXYYYJJEEfEEEJr   c                 z    t          | t                    s| g} d | D             } t          j        | d          } | S )N
        Convert a PIL image or a list of PIL images to NumPy arrays.
        c                 v    g | ]6}t          j        |                              t           j                  d z  7S )g     o@r   arrayrR   float32r#   s     r   rK   z2VaeImageProcessor.pil_to_numpy.<locals>.<listcomp>   s5    QQQ"(5//((44u<QQQr   r   axisr   r&   r   stackr(   s    r   pil_to_numpyzVaeImageProcessor.pil_to_numpyx   sI    
 &$'' 	XFQQ&QQQ&q)))r   c                     | j         dk    r| d         } t          j        |                     dddd                    } | S )z<
        Convert a NumPy image to a PyTorch tensor.
        r   ).Nr   r
   r   )r   r   
from_numpy	transposer(   s    r   numpy_to_ptzVaeImageProcessor.numpy_to_pt   sD    
 ;!I&F!&"2"21aA">">??r   c                     |                                                      dddd                                                                          } | S )z<
        Convert a PyTorch tensor to a NumPy image.
        r   r   r   r
   )cpupermutefloatnumpyr(   s    r   pt_to_numpyzVaeImageProcessor.pt_to_numpy   sB    
 %%aAq117799??AAr   c                     d| z  dz
  S )z5
        Normalize an image array to [-1,1].
        g       @g      ?rN   r(   s    r   	normalizezVaeImageProcessor.normalize   s    
 V|c!!r   c                 :    | dz  dz                        dd          S )z6
        Denormalize an image array to [0,1].
        r         ?r   r
   )clampr(   s    r   denormalizezVaeImageProcessor.denormalize   s#    
 
S ''1---r   r   c                 0    |                      d          } | S )z5
        Converts a PIL image to RGB format.
        RGBconvertr   s    r   convert_to_rgbz VaeImageProcessor.convert_to_rgb   s    
 e$$r   c                 0    |                      d          } | S )z;
        Converts a PIL image to grayscale format.
        rE   rt   r   s    r   convert_to_grayscalez&VaeImageProcessor.convert_to_grayscale   s    
 c""r   blur_factorc                 T    |                      t          j        |                    } | S )z4
        Applies Gaussian blur to an image.
        )filterr   GaussianBlur)r   ry   s     r   blurzVaeImageProcessor.blur   s%    
 [5kBBCCr   r   
mask_imagewidthheightc           	         |                      d          } t          j        |           }|j        \  }}d}t	          |          D ]+}|dd|f         dk                                    s n|dz  },d}	t          t	          |                    D ]+}|dd|f         dk                                    s n|	dz  }	,d}
t	          |          D ]'}||         dk                                    s n|
dz  }
(d}t          t	          |                    D ]'}||         dk                                    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  }||k    rr||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
        }nq||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.
        rE   r   Nr
   r   )ru   r   r[   rS   ranger'   reversedintmaxminr   r   )r~   r   r   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   sy   $  '',,
x
## z1	q 	 	AAJ!O((** NII
%((## 	 	AAJ!O((** !OJJq 	 	AGqL%%'' MHH%((## 	 	AGqL%%'' 1KK IOQ''((HsNA&&''A
NS(!,,--AOc)1--..	
BB  "Wb1 6>/// 2g)99N"%nR&@"A"A%**B%(;q(@@@BZ&&&J--d
d
AvvbbZ&&&&"W(88M!$]b2g%>!?!?$))B$'9Q'>>>BZ%%%J,,d
d
AvvbbZ%%%%2r2~r   c           	         ||z  }|j         |j        z  }||k     r|n|j         |z  |j        z  }||k    r|n|j        |z  |j         z  }|                    ||ft          d                   }t	          j        d||f          }	|	                    ||dz  |dz  z
  |dz  |dz  z
  f           ||k     r|dz  |dz  z
  }
|
dk    rs|	                    |                    ||
fdd|df          d           |	                    |                    ||
fd|j        ||j        f          d|
|z   f           n||k    r|dz  |dz  z
  }|dk    rs|	                    |                    ||fddd|f          d           |	                    |                    ||f|j         d|j         |f          ||z   df           |	S )an  
        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: The image to resize.
            width: The width to resize the image to.
            height: The height to resize the image to.
        r.   r2   rs   r   boxr   )r   r   r   r   resizer   r   newpaste)r;   r   r   r   ratio	src_ratiosrc_wsrc_hresizedresfill_height
fill_widths               r   _resize_and_fillz"VaeImageProcessor._resize_and_fill  s(     K%,.	**f0D0T9,,%,2F%+2U,,u~8I)8T,UUiv//		'
UaZ 71uPQz9QR	SSS9 A+
2KQ		'..%)=Aq%QRCS.TTZ`	aaa		NNE;#7aQVX_Xf=gNhhK%/0     Y!eqj0JA~~		'..*f)=Aq!VCT.UU[a	bbb		NNJ#7gmQPWP]_e=fNgg#e+Q/    
 
r   c                 b   ||z  }|j         |j        z  }||k    r|n|j         |z  |j        z  }||k    r|n|j        |z  |j         z  }|                    ||ft          d                   }t	          j        d||f          }	|	                    ||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: The image to resize.
            width: The width to resize the image to.
            height: The height to resize the image to.
        r.   r   rs   r   r   r   )
r;   r   r   r   r   r   r   r   r   r   s
             r   _resize_and_cropz"VaeImageProcessor._resize_and_cropG  s     K%,.	**f0D0T9,,%,2F%+2U,,u~8I)8T,UUiv//		'
UaZ 71uPQz9QR	SSS
r   defaultresize_modec                    |dk    r1t          |t          j        j                  st          d|           t          |t          j        j                  r|dk    r/|                    ||ft
          | j        j                           }n|dk    r|                     |||          }n|dk    r| 	                    |||          }nt          d| d          t          |t          j                  r)t          j        j                            |||f          }nlt          |t          j                  rR|                     |          }t          j        j                            |||f          }|                     |          }|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.
        r   z2Only PIL image input is supported for resize_mode r   fillcropzresize_mode  is not supported)size)r   r   r   r:   r   r   configr2   r   r   r   r   nn
functionalinterpolater   r   re   rk   )r;   r   r   r   r   s        r   r   zVaeImageProcessor.resizea  s   < )##Jucio,N,N#_R]__```eSY_-- 	,i''eV_?PQUQ\Qe?fgg&&--eUFCC&&--eUFCC !N!N!N!NOOOu|,, 	,H'33e_ 4  EE rz** 	,$$U++EH'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   ro   r
   rN   )r;   r   s     r   binarizezVaeImageProcessor.binarize  s%     eckeslr   Nc                     |\t          |t          j        j                  r|j        }n5t          |t          j                  r|j        d         }n|j        d         }|\t          |t          j        j                  r|j        }n5t          |t          j                  r|j        d         }n|j        d         } fd||fD             \  }}||fS )aF  
        This function return the height and width that are downscaled to the next integer multiple of
        `vae_scale_factor`.

        Args:
            image(`PIL.Image.Image`, `np.ndarray` or `torch.Tensor`):
                The image input, can be a PIL image, numpy array or pytorch tensor. if it is a numpy array, should have
                shape `[batch, height, width]` or `[batch, height, width, channel]` if it is a pytorch tensor, should
                have shape `[batch, channel, height, width]`.
            height (`int`, *optional*, defaults to `None`):
                The height in preprocessed image. If `None`, will use the height of `image` input.
            width (`int`, *optional*`, defaults to `None`):
                The width in preprocessed. If `None`, will use the width of the `image` input.
        Nr   r
   r   c              3   <   K   | ]}||j         j        z  z
  V  d S r"   )r   r0   )r$   xr;   s     r   r%   z=VaeImageProcessor.get_default_height_width.<locals>.<genexpr>  sC       
 
56ADK000
 
 
 
 
 
r   )r   r   r   r   r   r   rS   r   )r;   r   r   r   s   `   r   get_default_height_widthz*VaeImageProcessor.get_default_height_width  s    * >%11 (E5<00 (QQ=%11 'E5<00 'AA
 
 
 
;@&/
 
 
v u}r   crops_coordsc                 @
    t           j        j        t          j        t          j        f} j        j        rt          |t          j        t          j        f          ry|j	        dk    rnt          |t          j                  r|
                    d          }n>|j        d         dk    rt          j        |d          }nt          j        |d          }t          |t                    rat          |d         t          j                  rA|d         j	        dk    r0t          j        dt                      t          j        |d          }t          |t                    rat          |d         t          j                  rA|d         j	        dk    r0t          j        dt                      t	          j        |d          }t'          |          s/t)          d	d
                    d |D                                  t          |t                    s|g}t          |d         t           j        j                  rfd|D             } j        j        r1                     |d                   \   fd|D             } j        j        r fd|D             }n j        j        r fd|D             }                     |          }                     |          }nt          |d         t          j                  r|d         j	        dk    rt          j        |d          nt          j        |d          }                     |          }                     |          \   j        j        r                     |          }nt          |d         t          j                  r|d         j	        dk    rt	          j        |d          nt	          j        |d          } j        j        r |j	        dk    r|
                    d          }|j        d         }|dk    r|S                      |          \   j        j        r                     |          } j        j        }|r_|                                dk     rGt          j        d|                                 d|                                 dt                      d}|r                      |          } j        j!        r "                    |          }|S )at  
        Preprocess the image input.

        Args:
            image (`pipeline_image_input`):
                The image input, accepted formats are PIL images, NumPy arrays, PyTorch tensors; Also accept list of
                supported formats.
            height (`int`, *optional*, defaults to `None`):
                The height in preprocessed image. If `None`, will use the `get_default_height_width()` to get default
                height.
            width (`int`, *optional*`, defaults to `None`):
                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.
        r   r
   rB   r   r]   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   4   K   | ]}t          |          V  d S r"   )str)r$   r   s     r   r%   z/VaeImageProcessor.preprocess.<locals>.<genexpr>  s-      UxUxabVYZ[V\V\UxUxUxUxUxUxr   Nc                 :    g | ]}|                               S rN   )r   )r$   r   r   s     r   rK   z0VaeImageProcessor.preprocess.<locals>.<listcomp>   s%    ===!--===r   c                 B    g | ]}                     |           S ))r   r   )r$   r   r   r   r;   r   s     r   rK   z0VaeImageProcessor.preprocess.<locals>.<listcomp>#  s.    ___TUQ;OO___r   c                 :    g | ]}                     |          S rN   )rv   r$   r   r;   s     r   rK   z0VaeImageProcessor.preprocess.<locals>.<listcomp>%  s'    ???A,,Q//???r   c                 :    g | ]}                     |          S rN   )rx   r   s     r   rK   z0VaeImageProcessor.preprocess.<locals>.<listcomp>'  s'    EEE!22155EEEr   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   	unsqueezerS   expand_dimsr&   warningswarnFutureWarningconcatenatecatr*   r:   joinr/   r   r5   ra   re   r`   r   r3   r   r   rm   r4   r   )	r;   r   r   r   r   r   supported_formatschannelr3   s	   ` ````   r   
preprocesszVaeImageProcessor.preprocess  s;   > !Y_bj%,G ;+ 	;
55<QSQ[B\0]0] 	;bgblpqbqbq%.. ; **
 ;r?a''N5q999EEN5r:::EeT"" 	2z%(BJ'G'G 	2ERSHM]^L^L^Mn  
 N5q111EeT"" 	-z%(EL'I'I 	-eTUhm_`N`N`Mp  
 Ie!,,,E'.. 	zDIIUxUxfwUxUxUxLxLxzz   %&& 	GEeAh	00 #	:'====u==={$ ` $ = =eAhPU V V_______Y^___{) F???????1 FEEEEuEEE%%e,,E$$U++EEa"*-- 	:5:1X]a5G5GBN5q1111RXV[bcMdMdMdE$$U++E 99%OOMFE{$ :E6599a%,// 	:05a0B0BEIe!,,,,TY`aHbHbHbE{/ +EJ!OO**k!nG!|| 99%OOMFE{$ :E6599 {/ 	!EIIKK!OOMDglgpgpgrgrD Duzu~u~  vA  vAD D D  
 !L 	*NN5))E;" 	)MM%((Er   piloutput_typedo_denormalizec                     t          t          j                  s t          dt	                     d          |dvrd| d}t          dd|d	           d
}|dk    rS  j        j        gj        d         z  t          j	         fdt          j        d                   D                       |dk    rS                                |d
k    rS |dk    r                               S dS )  
        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   r   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   Nr   c                 f    g | ]-}|         r                     |                   n|         .S rN   rq   r$   r   r   r   r;   s     r   rK   z1VaeImageProcessor.postprocess.<locals>.<listcomp>~  >    jjjq>!+<JTeAh'''%(jjjr   r   r   )r   r   r   r:   typer   r   r3   rS   r`   r   rk   rV   )r;   r   r   r   deprecation_messages   `` ` r   postprocesszVaeImageProcessor.postprocessU  sV   , %.. 	qDKKqqq   ;;;.; . . .   /:M]bccccK(""L!"k67%+a.HNjjjjjjTYZ_ZefgZhTiTijjj
 
 $L  ''$L%$$U+++  r   r   
init_imagecrop_coordsc                 (   |j         |j        }}|                     |||          }|                     |||          }t          j                            d||f          }|                    |                    d                              d          t          j	        |                    d                               |                    d          }|y|\  }}	}
}|
|z
  }||	z
  }t          j                            d||f          }|                     |||d          }|                    |||	f           |                    d	          }|                    d          }|
                    |           |                    d	          }|S )
zB
        overlay the inpaint output to the original image
        )r   r   RGBaRGBArE   )r   Nr   )r   r   r   rs   )r   r   r   r   r   r   r   ru   r	   invertalpha_composite)r;   r   r   r   r   r   r   init_image_maskedr   yr   r   r   r   
base_images                  r   apply_overlayzVaeImageProcessor.apply_overlay  s~    U\v[[5[HH
{{4uV{<<IMM&5&/BB
 2 26 : : B B6 J JQYQ`aeamamnqararQsQsttt-55f=="&LAq"bQAQAvv??JKKaqfKMMEUQF+++&&u--Ef%%/000e$$r   )Tr-   r    r.   TFFF)r    )r   )r   )NN)NNr   Nr   Nr"   )*__name__
__module____qualname____doc__r   config_namer   boolr   r   r9   staticmethodr   r   r   r   r   rV   r   ra   r   r   re   rk   rm   rq   rv   rx   r}   r   r   r   r   r   r   r   r   PipelineImageInputr   r   r   __classcell__r<   s   @r   r,   r,   <   s,        * K  !#$!!!$%*   !	
     #     & RZ D,A    \ 	U4	#8#)/#IJ 	rz 	 	 	 \	 BJ 5<    \ EL RZ    \ "%
EL 89 "eBJPUP\D\>] " " " \" .E"*el":; .bjRWR^F^@_ . . . \. cio #)/    \ CIO 	    \  CIO # cio    \ W WCIO WC W W W W \Wr+y+ + 	+
 
+ + + +Zy  	
 
   > %6 6SY_bj%,>?6 6 	6
 6 
sy
EL8	96 6 6 6pcio #)/    ( !%#	) )SY_bj%,>?) ) }	)
 
sCx) ) ) )\ !%#$<@~ ~!~ ~ }	~
 ~ uS#sC%789~ 
~ ~ ~ ~F !/3	5, 5,|5, 5, !d,	5,
 
sy
EL8	95, 5, 5, 5,x <@! !io! IO! y	!
 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].
    Tr-   r.   r/   r0   r2   r3   c                 H    t                                                       d S r"   r8   r9   )r;   r/   r0   r2   r3   r<   s        r   r9   zVaeImageProcessorLDM3D.__init__  s!     	r   r)   r=   c                     | j         dk    r| d         } | dz                                                      d          } | j        d         dk    rd | D             }nd | D             }|S )	zL
        Convert a NumPy image or a batch of images to a PIL image.
        r   r?   r@   rA   rB   r
   c                 ^    g | ]*}t          j        |                                d           +S rD   rH   r#   s     r   rK   z7VaeImageProcessorLDM3D.numpy_to_pil.<locals>.<listcomp>  rL   r   c           	      T    g | ]%}t          j        |d d d d d df                   &S Nr   rO   r#   s     r   rK   z7VaeImageProcessorLDM3D.numpy_to_pil.<locals>.<listcomp>  s8    OOOu%/%111bqb/::OOOr   rP   rT   s     r   rV   z#VaeImageProcessorLDM3D.numpy_to_pil  s    
 ;!I&F3,%%''..w77<q  YYRXYYYJJOOOOOJr   c                 z    t          | t                    s| g} d | D             } t          j        | d          } | S )rX   c                 v    g | ]6}t          j        |                              t           j                  d z  7S )i  rZ   r#   s     r   rK   z=VaeImageProcessorLDM3D.depth_pil_to_numpy.<locals>.<listcomp>  s5    WWWu"(5//((44	BWWWr   r   r]   r_   r(   s    r   depth_pil_to_numpyz)VaeImageProcessorLDM3D.depth_pil_to_numpy  sJ    
 &$'' 	XFWWPVWWW&q)))r   r   c                 F    | dddddf         dz  | dddddf         z   S )z\
        Args:
            image: RGB-like depth image

        Returns: depth map

        Nr
      r   rN   r   s    r   rgblike_to_depthmapz*VaeImageProcessorLDM3D.rgblike_to_depthmap  s8     QQQ1W~$uQQQ1W~55r   c                     |j         dk    r|d         }|ddddddddf         }|j        d         dk    r9|dz                                                      d          } fd|D             }nO|j        d         d	k    r/|d
z                      t          j                  }d |D             }nt          d          |S )zR
        Convert a NumPy depth image or a batch of images to a PIL image.
        r   r?   NrB      r@   rA   c                 b    g | ]+}t          j                            |          d           ,S zI;16rF   )r   rI   r  )r$   image_depthr;   s     r   rK   z9VaeImageProcessorLDM3D.numpy_to_depth.<locals>.<listcomp>  sC       Xc 8 8 E EFSSS  r   r    g    @c                 :    g | ]}t          j        |d           S r  rO   )r$   r  s     r   rK   z9VaeImageProcessorLDM3D.numpy_to_depth.<locals>.<listcomp>   s'    ddd%/+FCCCdddr   zNot supported)r   rS   rQ   rR   r   uint16	Exception)r;   r)   images_depthrU   s   `   r   numpy_to_depthz%VaeImageProcessorLDM3D.numpy_to_depth  s     ;!I&FaaaAAAqrrk*<q  (3.5577>>wGGL   gs  JJ \"""(72::29EELddWcdddJJO,,,r   r   Nr   r   c                     t          t          j                  s t          dt	                     d          |dvrd| d}t          dd|d	           d
} j        j        gj        d         z  t          j	         fdt          j        d                   D                                                      |d
k    r^j        d         dk    r#t          j	         fdD             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*                                                              fS t          d| d          )r   r   r   r   r   r   r   r   Fr   r   Nr   c                 f    g | ]-}|         r                     |                   n|         .S rN   r   r   s     r   rK   z6VaeImageProcessorLDM3D.postprocess.<locals>.<listcomp>,  r   r   rB   r  c           	      X    g | ]&}                     |d d d d dd f                   'S r  )r  )r$   imr;   s     r   rK   z6VaeImageProcessorLDM3D.postprocess.<locals>.<listcomp>3  s>    '_'_'_SU(@(@AAAqqq!""H(N(N'_'_'_r   r]   r   r   z
This type r   )r   r   r   r:   r   r   r   r3   rS   r`   r   rk   r   rV   r  r  )r;   r   r   r   r   r  s   `` `  r   r   z"VaeImageProcessorLDM3D.postprocess  s   , %.. 	qDKKqqq   ;;;.; . . .   /:M]bccccK!"k67%+a.HNjjjjjjTYZ_ZefgZhTiTijjj
 
   ''${2!## h'_'_'_'_Y^'_'_'_fghhh#AAAqqq!!!QRRK0AAAqqq"1"%{22%$$U++T-@-@-G-GGGGGGGHHHr   rgbdepthr   r   
target_resc                 8    t           j        j        t          j        t          j        f j        j        r@t          |t          j        t          j        f          r|j	        dk    rt          d          t          |          r|g}|g}nbt          |t                    rt          fd|D                       s2t          dd |D              dd                                         t          |d         t           j        j                  rÉ j        j        rt          d           j        j        s|rD|s                     |d                   n|\   fd	|D             } fd
|D             }                     |          }                     |          }                     |          }                     |          }not          |d         t          j                  r|d         j	        dk    rt          j        |d          nt          j        |d          }                     |          }                     |          \   j        j        r                     |          }|d         j	        dk    rt          j        |d          nt          j        |d          }                     |          }                     |          \   j        j        r                     |          }n/t          |d         t          j                  rt          d           j        j        }|                                dk     rI|rGt5          j        d|                                 d|                                 dt:                     d}|r*                     |          }                     |          } j        j        r*                      |          }                      |          }||fS )zo
        Preprocess the image input. Accepted formats are PIL images, NumPy arrays or PyTorch tensors.
        r   zThis is not yet supportedc              3   8   K   | ]}t          |          V  d S r"   )r   )r$   r   r   s     r   r%   z4VaeImageProcessorLDM3D.preprocess.<locals>.<genexpr>Q  s/      /^/^UV
1>O0P0P/^/^/^/^/^/^r   zInput is in incorrect format: c                 ,    g | ]}t          |          S rN   )r   )r$   r   s     r   rK   z5VaeImageProcessorLDM3D.preprocess.<locals>.<listcomp>S  s    1G1G1Ga$q''1G1G1Gr   z. Currently, we only support r   r   c                 >    g | ]}                     |          S rN   r   r$   r   r   r;   r   s     r   rK   z5VaeImageProcessorLDM3D.preprocess.<locals>.<listcomp>]  s)    BBBt{{1fe44BBBr   c                 >    g | ]}                     |          S rN   r   r)  s     r   rK   z5VaeImageProcessorLDM3D.preprocess.<locals>.<listcomp>^  s)    FFF1Q66FFFr   r    r]   r   r   r   F)!r   r   r   r   r   r   r   r6   r   r   r  r&   r'   r:   r   r5   r/   r   ra   re   r  r   r`   r   r3   r   r   r   r   r   rm   r4   r   )r;   r"  r#  r   r   r$  r3   r   s   `  ``  @r   r   z!VaeImageProcessorLDM3D.preprocess=  s[    !Y_bj%,G ;+ 	9
3rz@Z0[0[ 	9`c`hlm`m`m7888c,-- 	%CGEES$'' 	C/^/^/^/^Z]/^/^/^,^,^ 	 E1G1G31G1G1G  E  Efjfofo  qB  gC  gC  E  E   c!fcio.. 	9{) = ;<<< {$ G
 G\f v = =c!ffe T T TlvBBBBBBcBBBFFFFFFFFF##C((C""3''C++E22E$$U++EEA
++ 	914Q1A1A".1----rxPSZ[G\G\G\C""3''C 99#vuMMMFE{$ 6kk#vu5558V[A5E5EBN5q111128TY`aKbKbKbE$$U++E 99%OOMFE{$ :E6599A-- 	978884 {/7799q==\=M@gjgngngpgp@ @svszszs|s|@ @ @  
 !L 	*..%%CNN5))E;" 	)--$$CMM%((EEzr   )Tr-   r.   Tr   )NNN)r   r   r   r   r   r   r   r  r   r   r9   r  r   r   r   r   r   rV   r   r  r   r   r  r  r   r   r   r  r  s   @r   r  r    s         K  !!!   	
       RZ D,A    \ 	5cio)>	)O#P 	UWU_ 	 	 	 \	 65U\)A#B 6uRZY^YeMeGf 6 6 6 \6RZ D4I    . !/3	5I 5I|5I 5I !d,	5I
 
sy
EL8	95I 5I 5I 5Iv !%#$(a a5<"*<=a U\39?BJ>?a 	a
 }a SMa 
a a a a a a a a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.

    Tr-   r.   Fr/   r0   r2   r3   r4   r6   c                 V    t                                          ||||||           d S N)r/   r0   r2   r3   r4   r6   r	  r;   r/   r0   r2   r3   r4   r6   r<   s          r   r9   zIPAdapterMaskProcessor.__init__  B     	-%#!5 	 	
 	
 	
 	
 	
r   r   
batch_sizenum_queriesvalue_embed_dimc                    | j         d         }| j         d         }||z  }t          t          j        ||z                      }t          |          t          |t          |          z  dk              z   }||z  }t	          j        |                     d          ||fd                              d          }	|	j         d         |k     r|	                    |dd          }	|		                    |	j         d         d          }	||z  }
|
|k     rAt          j        dt                     t	          j        |	d||	j         d         z
  fd	          }	|
|k    r(t          j        dt                     |	d
d
d
|f         }	|		                    |	j         d         |	j         d         d                              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   rG   rB   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)rS   r   mathsqrtFr   r   rJ   repeatviewr   r   UserWarningr   )r   r1  r2  r3  o_ho_wr   mask_hmask_wmask_downsampledownsampled_areas              r   
downsamplez!IPAdapterMaskProcessor.downsample  s   * jmjmc	TY{U23344VsK#f++$=!#CDDD&-q(9(9@PW`aaaiijkll  #j00-44ZAFFO)../DQ/GLL!F? k))M^  
  eOaG\]^G_9_5`hklllOk))M^  
 .aaa+o>O *../DQ/GI^_`Iacdeellq/
 
 r   )Tr-   r.   FTT)r   r   r   r   r   r   r   r  r   r   r9   r  r   r   rC  r  r  s   @r   r,  r,    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.
    Tr-   r.   Fr/   r0   r2   r3   r4   r6   c                 V    t                                          ||||||           d S r.  r	  r/  s          r   r9   zPixArtImageProcessor.__init__  r0  r   r   r   ratiosr=   c                     t          | |z            t          |                                fd          }||         }t          |d                   t          |d                   fS )z Returns binned height and width.c                 B    t          t          |           z
            S r"   )absri   )r   ars    r   <lambda>z@PixArtImageProcessor.classify_height_width_bin.<locals>.<lambda>6  s    SuPRAR=S=S r   )keyr   r
   )ri   r   keysr   )r   r   rG  closest_ratio
default_hwrK  s        @r   classify_height_width_binz.PixArtImageProcessor.classify_height_width_bin2  sg     6E>""FKKMM/S/S/S/STTTM*
:a=!!3z!}#5#555r   samples	new_width
new_heightc                 V   | j         d         | j         d         }}||k    s||k    rt          ||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 )Nr   r   bilinearF)r   rG   align_corners)rS   r   r   r9  r   )rR  rS  rT  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    ")-"2GM!4DZ *$$
i(?(?
[0)j2HIIE
U 233M u!455N m~}=J^c  G
 %y0Q6Gi'E%
2q8Gj(EaaaGEM75=@AGr   )Tr-   r.   TFF)r   r   r   r   r   r  r   r   r9   r  dictr   rQ  r   r   r`  r  r  s   @r   rE  rE  	  s1        *   !!!!%*
 

 
 	

 
 
 #
 
 
 
 
 
$ 6# 6c 64 6ERUWZRZO 6 6 6 \6   RU Z_Zf    \    r   rE  )$r7  r   typingr   r   r   r   rj   r   	PIL.Imager   r   torch.nn.functionalr   r   r9  r   r   r	   configuration_utilsr   r   utilsr   r   r   r   r   r  PipelineDepthInputr   r*   r,   r  r,  rE  rN   r   r   <module>rh     s     / / / / / / / / / / / /                   , , , , , , , , , , @ @ @ @ @ @ @ @ < < < < < < < < < < IOJ	L  ( x x x  q	 q	 q	 q	 q	 q	 q	 q	hn n n n n. n n nbe e e e e. e e ePG G G G G, G G G G Gr   