
    bin'                     ^   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Z ddlmZ ddlmZmZmZ ddlmZ dd	lmZmZ  ej.                  e      Zd
eeej4                  j4                  e	j6                  f   fdZdeeej4                  j4                  e	j6                  f   fdZ G d de      Zy)    )ListOptionalTupleUnionN   )UNet2DModel)RePaintScheduler)PIL_INTERPOLATION	deprecatelogging)randn_tensor   )DiffusionPipelineImagePipelineOutputimagec           
      2   d}t        dd|d       t        | t        j                        r| S t        | t        j
                  j
                        r| g} t        | d   t        j
                  j
                        r| d   j                  \  }}d ||fD        \  }}| D cg c]8  }t        j                  |j                  ||ft        d   	            d d d f   : } }t        j                  | d
      } t        j                  |       j                  t        j                        dz  } | j                  dddd      } d| z  dz
  } t        j                  |       } | S t        | d   t        j                        rt        j                   | d      } | S c c}w )NzThe preprocess method is deprecated and will be removed in diffusers 1.0.0. Please use VaeImageProcessor.preprocess(...) instead
preprocessz1.0.0F)standard_warnr   c              3   ,   K   | ]  }||d z  z
    yw)   N .0xs     r/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/pipelines/deprecated/repaint/pipeline_repaint.py	<genexpr>z$_preprocess_image.<locals>.<genexpr>+   s     *aAE	*   lanczosresampleaxis     o@r         g       @g      ?dim)r   
isinstancetorchTensorPILImagesizenparrayresizer
   concatenateastypefloat32	transpose
from_numpycat)r   deprecation_messagewhis        r   _preprocess_imager;   !   sX    ]lG%8N%&	E399??	+%(CIIOO,Qx}}1*Aq6*1ejk`a!((Aq64Ei4P(QRSWYZSZ[kku1-&&rzz2U:1a+ec!  ' L 
E!Hell	+		%Q'L ls    =Fmaskc           
         t        | t        j                        r| S t        | t        j                  j                        r| g} t        | d   t        j                  j                        r| d   j
                  \  }}d ||fD        \  }}| D cg c]G  }t        j                  |j                  d      j                  ||ft        d               d d d f   I } }t        j                  | d      } | j                  t        j                        dz  } d| | dk  <   d	| | dk\  <   t        j                  |       } | S t        | d   t        j                        rt        j                  | d
      } | S c c}w )Nr   c              3   ,   K   | ]  }||d z  z
    yw)    Nr   r   s     r   r   z#_preprocess_mask.<locals>.<genexpr>@   s     +qAF
+r   Lnearestr   r!   r#         ?r$   r&   )r(   r)   r*   r+   r,   r-   r.   r/   convertr0   r
   r1   r2   r3   r5   r6   )r<   r8   r9   ms       r   _preprocess_maskrE   8   s<   $%	D#))//	*v$q'399??+Aw||1+QF+1quvlm3..1v@QR[@\.]^_cef_fgvv~~d+{{2::&.TCZTS[% K 
DGU\\	*yy1%K ws   AE3c                       e Zd ZU dZeed<   eed<   dZdedef fdZ e	j                         	 	 	 	 	 	 	 ddee	j                  ej                  j                  f   dee	j                  ej                  j                  f   deded	ed
edeee	j$                  ee	j$                     f      dee   dedeeef   fd       Z xZS )RePaintPipelinea  
    Pipeline for image inpainting using RePaint.

    This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
    implemented for all pipelines (downloading, saving, running on a particular device, etc.).

    Parameters:
        unet ([`UNet2DModel`]):
            A `UNet2DModel` to denoise the encoded image latents.
        scheduler ([`RePaintScheduler`]):
            A `RePaintScheduler` to be used in combination with `unet` to denoise the encoded image.
    unet	schedulerc                 H    t         |           | j                  ||       y )N)rH   rI   )super__init__register_modules)selfrH   rI   	__class__s      r   rL   zRePaintPipeline.__init__^   s!    49=    r   
mask_imagenum_inference_stepsetajump_lengthjump_n_sample	generatoroutput_typereturn_dictreturnc
           	         |}
t        |
      }
|
j                  | j                  | j                  j                        }
t        |      }|j                  | j                  | j                  j                        }|
j                  d   }t        |t              r)t        |      |k7  rt        dt        |       d| d      |
j                  }t        ||| j                  | j                  j                        }| j                  j                  |||| j                         || j                  _        | j                  j                  d   dz   }t        |t              r|d   n|}t!        | j#                  | j                  j                              D ]p  \  }}||k  rG| j                  ||      j$                  }| j                  j'                  ||||
||      j(                  }n| j                  j+                  |||      }|}r |dz  d	z   j-                  dd      }|j/                         j1                  ddd
d      j3                         }|dk(  r| j5                  |      }|	s|fS t7        |      S )a  
        The call function to the pipeline for generation.

        Args:
            image (`torch.Tensor` or `PIL.Image.Image`):
                The original image to inpaint on.
            mask_image (`torch.Tensor` or `PIL.Image.Image`):
                The mask_image where 0.0 define which part of the original image to inpaint.
            num_inference_steps (`int`, *optional*, defaults to 1000):
                The number of denoising steps. More denoising steps usually lead to a higher quality image at the
                expense of slower inference.
            eta (`float`):
                The weight of the added noise in a diffusion step. Its value is between 0.0 and 1.0; 0.0 corresponds to
                DDIM and 1.0 is the DDPM scheduler.
            jump_length (`int`, *optional*, defaults to 10):
                The number of steps taken forward in time before going backward in time for a single jump ("j" in
                RePaint paper). Take a look at Figure 9 and 10 in the
                [paper](https://huggingface.co/papers/2201.09865).
            jump_n_sample (`int`, *optional*, defaults to 10):
                The number of times to make a forward time jump for a given chosen time sample. Take a look at Figure 9
                and 10 in the [paper](https://huggingface.co/papers/2201.09865).
            generator (`torch.Generator`, *optional*):
                A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
                generation deterministic.
            output_type (`str`, `optional`, defaults to `"pil"`):
                The output format of the generated image. Choose between `PIL.Image` or `np.array`.
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.

        Example:

        ```py
        >>> from io import BytesIO
        >>> import torch
        >>> import PIL
        >>> import requests
        >>> from diffusers import RePaintPipeline, RePaintScheduler


        >>> def download_image(url):
        ...     response = requests.get(url)
        ...     return PIL.Image.open(BytesIO(response.content)).convert("RGB")


        >>> img_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/celeba_hq_256.png"
        >>> mask_url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png"

        >>> # Load the original image and the mask as PIL images
        >>> original_image = download_image(img_url).resize((256, 256))
        >>> mask_image = download_image(mask_url).resize((256, 256))

        >>> # Load the RePaint scheduler and pipeline based on a pretrained DDPM model
        >>> scheduler = RePaintScheduler.from_pretrained("google/ddpm-ema-celebahq-256")
        >>> pipe = RePaintPipeline.from_pretrained("google/ddpm-ema-celebahq-256", scheduler=scheduler)
        >>> pipe = pipe.to("cuda")

        >>> generator = torch.Generator(device="cuda").manual_seed(0)
        >>> output = pipe(
        ...     image=original_image,
        ...     mask_image=mask_image,
        ...     num_inference_steps=250,
        ...     eta=0.0,
        ...     jump_length=10,
        ...     jump_n_sample=10,
        ...     generator=generator,
        ... )
        >>> inpainted_image = output.images[0]
        ```

        Returns:
            [`~pipelines.ImagePipelineOutput`] or `tuple`:
                If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
                returned where the first element is a list with the generated images.
        )devicedtyper   z/You have passed a list of generators of length z+, but requested an effective batch size of z@. Make sure the batch size matches the length of the generators.)rV   r[   r\   r$   r%   rB   r   pil)images)r;   to_execution_devicerH   r\   rE   shaper(   listlen
ValueErrorr   rI   set_timestepsrS   	timesteps	enumerateprogress_barsamplestepprev_sample	undo_stepclampcpupermutenumpynumpy_to_pilr   )rN   r   rQ   rR   rS   rT   rU   rV   rW   rX   original_image
batch_sizeimage_shapet_lastr:   tmodel_outputs                    r   __call__zRePaintPipeline.__call__b   sB   p *>:'**$2H2HPTPYPYP_P_*`%j1
]]$*@*@		]X
#))!,
 i&3y>Z+GA#i.AQ R&<'gi 
 %**[IdF\F\dhdmdmdsdst 	$$%8+}VZVlVlm ))!,q0$.y$$?IaLY	d//0H0HIJ 
	DAq6z#yy299++L!UNT^`ijvv 00	JF
	 S''1-		##Aq!Q/557%%%e,E8O"%00rP   )   g        
   rz   Nr]   T)__name__
__module____qualname____doc__r   __annotations__r	   model_cpu_offload_seqrL   r)   no_gradr   r*   r+   r,   intfloatr   	Generatorr   strboolr   r   rx   __classcell__)rO   s   @r   rG   rG   L   s(    ">[ >5E > U]]_
 $'MQ%* D1U\\399??23D1 %,,		78D1 !	D1
 D1 D1 D1 E%//43H"HIJD1 c]D1 D1 
"E)	*D1 D1rP   rG   )typingr   r   r   r   rp   r.   	PIL.Imager+   r)   modelsr   
schedulersr	   utilsr
   r   r   utils.torch_utilsr   pipeline_utilsr   r   
get_loggerr{   loggerr,   r*   r;   rE   rG   r   rP   r   <module>r      s     0 /    " + ; ; . D 
		H	%U4%,,#FG .5syy!DE ([1' [1rP   