



"""simple docstring"""
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


lowerCamelCase_       =		logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase_       =		"\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to(\"cuda\")\n\n        >>> prompt = \"A red cartoon frog, 4k\"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to(\"cuda\")\n\n        >>> init_image = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/frog.png\"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save(\"red_frog.png\")\n        ```\n"



def 					__lowerCamelCase       (							a_					:		Optional[int]			,       a_					:		List[str]			,       a_					:		int=8							)      ->				List[Any]:
      __SCREAMING_SNAKE_CASE       :Optional[int]		    =  height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      __SCREAMING_SNAKE_CASE       :Any		    =  width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor



def 					__lowerCamelCase       (							a_					:		Any			,       a_					:		str=5_12			,       a_					:		Union[str, Any]=5_12							)      ->				Any:
      __SCREAMING_SNAKE_CASE       :List[str]		    =  pil_image.resize((w, h)			,       resample=Image.BICUBIC			,       reducing_gap=1							)
      __SCREAMING_SNAKE_CASE       :int		    =  np.array(pil_image.convert('''RGB'''							)							)
      __SCREAMING_SNAKE_CASE       :Dict		    =  arr.astype(np.floataa							) / 127.5 - 1
      __SCREAMING_SNAKE_CASE       :List[Any]		    =  np.transpose(__lowerCAmelCase			,       [2, 0, 1]							)
      __SCREAMING_SNAKE_CASE       :int		    =  torch.from_numpy(__lowerCAmelCase							).unsqueeze(0							)
      return image







class  _SCREAMING_SNAKE_CASE(       lowerCamelCase__  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,)      ->				int:





             """simple docstring"""






             super().__init__()

             self.register_modules(
                 unet=snake_case__		,scheduler=snake_case__		,movq=snake_case__		,)
             __SCREAMING_SNAKE_CASE       :List[str]		    =  2 ** (len(self.movq.config.block_out_channels							) - 1)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__							)      ->				Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :int		    =  min(int(num_inference_steps * strength							)		,snake_case__							)

             __SCREAMING_SNAKE_CASE       :str		    =  max(num_inference_steps - init_timestep		,0							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  self.scheduler.timesteps[t_start:]

             return timesteps, num_inference_steps - t_start




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=None							)      ->				Optional[int]:





             """simple docstring"""






             if not isinstance(snake_case__		,(torch.Tensor, PIL.Image.Image, list)							):
                   raise ValueError(
                       f'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(snake_case__							)}'''							)

             __SCREAMING_SNAKE_CASE       :Dict		    =  image.to(device=snake_case__		,dtype=snake_case__							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  batch_size * num_images_per_prompt

             if image.shape[1] == 4:
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  image

             else:
                   if isinstance(snake_case__		,snake_case__							) and len(snake_case__							) != batch_size:
                         raise ValueError(
                             f'''You have passed a list of generators of length {len(snake_case__							)}, but requested an effective batch'''
                             f''' size of {batch_size}. Make sure the batch size matches the length of the generators.'''							)

                   elif isinstance(snake_case__		,snake_case__							):
                         __SCREAMING_SNAKE_CASE       :List[Any]		    =  [
                             self.movq.encode(image[i : i + 1]							).latent_dist.sample(generator[i]							) for i in range(snake_case__							)
                         ]
                         __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  torch.cat(snake_case__		,dim=0							)
                   else:
                         __SCREAMING_SNAKE_CASE       :Tuple		    =  self.movq.encode(snake_case__							).latent_dist.sample(snake_case__							)

                   __SCREAMING_SNAKE_CASE       :List[str]		    =  self.movq.config.scaling_factor * init_latents

             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  torch.cat([init_latents]		,dim=0							)

             __SCREAMING_SNAKE_CASE       :Any		    =  init_latents.shape
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  randn_tensor(snake_case__		,generator=snake_case__		,device=snake_case__		,dtype=snake_case__							)

             # get latents
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  self.scheduler.add_noise(snake_case__		,snake_case__		,snake_case__							)

             __SCREAMING_SNAKE_CASE       :Tuple		    =  init_latents

             return latents




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__=0							)      ->				Any:





             """simple docstring"""






             if is_accelerate_available():
                   from accelerate import cpu_offload
             else:
                   raise ImportError('''Please install accelerate via `pip install accelerate`'''							)

             __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.device(f'''cuda:{gpu_id}'''							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  [
                 self.unet,
                 self.movq,
             ]
             for cpu_offloaded_model in models:
                   if cpu_offloaded_model is not None:
                         cpu_offload(snake_case__		,snake_case__							)




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__=0							)      ->				Any:





             """simple docstring"""






             if is_accelerate_available() and is_accelerate_version('''>='''		,'''0.17.0.dev0'''							):
                   from accelerate import cpu_offload_with_hook
             else:
                   raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  torch.device(f'''cuda:{gpu_id}'''							)

             if self.device.type != "cpu":
                   self.to('''cpu'''		,silence_dtype_warnings=snake_case__							)
                   torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

             __SCREAMING_SNAKE_CASE       :List[str]		    =  None
             for cpu_offloaded_model in [self.unet, self.movq]:
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  cpu_offload_with_hook(snake_case__		,snake_case__		,prev_module_hook=snake_case__							)

             # We'll offload the last model manually.
             __SCREAMING_SNAKE_CASE       :Tuple		    =  hook




       @property
       # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
       def    _UpperCamelCase					(						self							)      ->				Optional[Any]:





             """simple docstring"""






             if not hasattr(self.unet		,'''_hf_hook'''							):
                   return self.device
             for module in self.unet.modules():
                   if (
                       hasattr(snake_case__		,'''_hf_hook'''							)
                       and hasattr(module._hf_hook		,'''execution_device'''							)
                       and module._hf_hook.execution_device is not None
                   ):
                         return torch.device(module._hf_hook.execution_device							)
             return self.device




       @torch.no_grad()
       @replace_example_docstring(snake_case__							)
       def __call__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = 5_12		,SCREAMING_SNAKE_CASE__ = 5_12		,SCREAMING_SNAKE_CASE__ = 1_00		,SCREAMING_SNAKE_CASE__ = 4.0		,SCREAMING_SNAKE_CASE__ = 0.3		,SCREAMING_SNAKE_CASE__ = 1		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = "pil"		,SCREAMING_SNAKE_CASE__ = True		,)      ->				int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  self._execution_device

             __SCREAMING_SNAKE_CASE       :Dict		    =  guidance_scale > 1.0

             if isinstance(snake_case__		,snake_case__							):
                   __SCREAMING_SNAKE_CASE       :Tuple		    =  torch.cat(snake_case__		,dim=0							)
             __SCREAMING_SNAKE_CASE       :str		    =  image_embeds.shape[0]
             if isinstance(snake_case__		,snake_case__							):
                   __SCREAMING_SNAKE_CASE       :Any		    =  torch.cat(snake_case__		,dim=0							)

             if do_classifier_free_guidance:
                   __SCREAMING_SNAKE_CASE       :int		    =  image_embeds.repeat_interleave(snake_case__		,dim=0							)
                   __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  negative_image_embeds.repeat_interleave(snake_case__		,dim=0							)

             __SCREAMING_SNAKE_CASE       :Dict		    =  torch.cat([negative_image_embeds, image_embeds]		,dim=0							).to(dtype=self.unet.dtype		,device=snake_case__							)

             if not isinstance(snake_case__		,snake_case__							):
                   __SCREAMING_SNAKE_CASE       :str		    =  [image]
             if not all(isinstance(snake_case__		,(PIL.Image.Image, torch.Tensor)							) for i in image							):
                   raise ValueError(
                       f'''Input is in incorrect format: {[type(snake_case__							) for i in image]}. Currently, we only support  PIL image and pytorch tensor'''							)

             __SCREAMING_SNAKE_CASE       :List[Any]		    =  torch.cat([prepare_image(snake_case__		,snake_case__		,snake_case__							) for i in image]		,dim=0							)
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  image.to(dtype=image_embeds.dtype		,device=snake_case__							)

             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  self.movq.encode(snake_case__							)['''latents''']
             __SCREAMING_SNAKE_CASE       :Dict		    =  latents.repeat_interleave(snake_case__		,dim=0							)
             self.scheduler.set_timesteps(snake_case__		,device=snake_case__							)
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  self.get_timesteps(snake_case__		,snake_case__		,snake_case__							)
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  timesteps[:1].repeat(batch_size * num_images_per_prompt							)
             __SCREAMING_SNAKE_CASE       :Tuple		    =  downscale_height_and_width(snake_case__		,snake_case__		,self.movq_scale_factor							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  self.prepare_latents(
                 snake_case__		,snake_case__		,snake_case__		,snake_case__		,image_embeds.dtype		,snake_case__		,snake_case__							)
             for i, t in enumerate(self.progress_bar(snake_case__							)							):
                   # expand the latents if we are doing classifier free guidance
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.cat([latents] * 2							) if do_classifier_free_guidance else latents

                   __SCREAMING_SNAKE_CASE       :Optional[int]		    =  {'''image_embeds''': image_embeds}
                   __SCREAMING_SNAKE_CASE       :int		    =  self.unet(
                       sample=snake_case__		,timestep=snake_case__		,encoder_hidden_states=snake_case__		,added_cond_kwargs=snake_case__		,return_dict=snake_case__		,)[0]

                   if do_classifier_free_guidance:
                         __SCREAMING_SNAKE_CASE       :List[Any]		    =  noise_pred.split(latents.shape[1]		,dim=1							)
                         __SCREAMING_SNAKE_CASE       :List[str]		    =  noise_pred.chunk(2							)
                         __SCREAMING_SNAKE_CASE       :Dict		    =  variance_pred.chunk(2							)
                         __SCREAMING_SNAKE_CASE       :int		    =  noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                         __SCREAMING_SNAKE_CASE       :int		    =  torch.cat([noise_pred, variance_pred_text]		,dim=1							)

                   if not (
                       hasattr(self.scheduler.config		,'''variance_type'''							)
                       and self.scheduler.config.variance_type in ["learned", "learned_range"]
                   ):
                         __SCREAMING_SNAKE_CASE       :str		    =  noise_pred.split(latents.shape[1]		,dim=1							)

                   # compute the previous noisy sample x_t -> x_t-1
                   __SCREAMING_SNAKE_CASE       :str		    =  self.scheduler.step(
                       snake_case__		,snake_case__		,snake_case__		,generator=snake_case__		,)[0]

             # post-processing
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  self.movq.decode(snake_case__		,force_not_quantize=snake_case__							)['''sample''']

             if output_type not in ["pt", "np", "pil"]:
                   raise ValueError(f'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'''							)

             if output_type in ["np", "pil"]:
                   __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  image * 0.5 + 0.5
                   __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  image.clamp(0		,1							)
                   __SCREAMING_SNAKE_CASE       :str		    =  image.cpu().permute(0		,2		,3		,1							).float().numpy()

             if output_type == "pil":
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  self.numpy_to_pil(snake_case__							)

             if not return_dict:
                   return (image,)

             return ImagePipelineOutput(images=snake_case__							)






"""simple docstring"""
from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_       =		logging.get_logger(__name__)

lowerCamelCase_       =		{
    "facebook/levit-128S": "https://huggingface.co/facebook/levit-128S/resolve/main/config.json",
    # See all LeViT models at https://huggingface.co/models?filter=levit
}






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				List[Any]     						=  '''levit'''




       def __init__(						self		,SCREAMING_SNAKE_CASE__=2_24		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=2		,SCREAMING_SNAKE_CASE__=1		,SCREAMING_SNAKE_CASE__=16		,SCREAMING_SNAKE_CASE__=[1_28, 2_56, 3_84]		,SCREAMING_SNAKE_CASE__=[4, 8, 12]		,SCREAMING_SNAKE_CASE__=[4, 4, 4]		,SCREAMING_SNAKE_CASE__=[16, 16, 16]		,SCREAMING_SNAKE_CASE__=0		,SCREAMING_SNAKE_CASE__=[2, 2, 2]		,SCREAMING_SNAKE_CASE__=[2, 2, 2]		,SCREAMING_SNAKE_CASE__=0.0_2		,**SCREAMING_SNAKE_CASE__		,)      ->				Tuple:





             """simple docstring"""






             super().__init__(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE       :Dict		    =  image_size
             __SCREAMING_SNAKE_CASE       :Dict		    =  num_channels
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  kernel_size
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  stride
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  padding
             __SCREAMING_SNAKE_CASE       :Tuple		    =  hidden_sizes
             __SCREAMING_SNAKE_CASE       :List[str]		    =  num_attention_heads
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  depths
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  key_dim
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  drop_path_rate
             __SCREAMING_SNAKE_CASE       :Tuple		    =  patch_size
             __SCREAMING_SNAKE_CASE       :int		    =  attention_ratio
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  mlp_ratio
             __SCREAMING_SNAKE_CASE       :str		    =  initializer_range
             __SCREAMING_SNAKE_CASE       :Optional[Any]		    =  [
                 ['''Subsample''', key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
                 ['''Subsample''', key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
             ]






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				int     						=  version.parse('''1.11'''  )




       @property
       def    _UpperCamelCase					(						self							)      ->				Mapping[str, Mapping[int, str]]:





             """simple docstring"""






             return OrderedDict(
                 [
                     ('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
                 ]							)




       @property
       def    _UpperCamelCase					(						self							)      ->				float:





             """simple docstring"""






             return 1E-4