






"""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,
)


UpperCAmelCase_   : Optional[int]   			= logging.get_logger(__name__)  # pylint: disable=invalid-name

UpperCAmelCase_   : Union[str, Any]   			= '''
    Examples:
        ```py
        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline
        >>> from diffusers.utils import load_image
        >>> import torch

        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16
        ... )
        >>> pipe_prior.to("cuda")

        >>> prompt = "A red cartoon frog, 4k"
        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)

        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(
        ...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16
        ... )
        >>> pipe.to("cuda")

        >>> init_image = load_image(
        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
        ...     "/kandinsky/frog.png"
        ... )

        >>> image = pipe(
        ...     image=init_image,
        ...     image_embeds=image_emb,
        ...     negative_image_embeds=zero_image_emb,
        ...     height=768,
        ...     width=768,
        ...     num_inference_steps=100,
        ...     strength=0.2,
        ... ).images

        >>> image[0].save("red_frog.png")
        ```
'''



def 					_A			(__a    ,				__a    ,				__a=8							) ->       str:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  List[Any]    						=		height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    SCREAMING_SNAKE_CASE_      :  List[str]    						=		width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor



def 					_A			(__a    ,				__a=5_12    ,				__a=5_12							) ->       Any:
    """simple docstring"""






    SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		pil_image.resize((w, h)    ,				resample=Image.BICUBIC    ,				reducing_gap=1							)
    SCREAMING_SNAKE_CASE_      :  List[str]    						=		np.array(pil_image.convert('''RGB'''							)							)
    SCREAMING_SNAKE_CASE_      :  Tuple    						=		arr.astype(np.floataa							) / 1_27.5 - 1
    SCREAMING_SNAKE_CASE_      :  Any    						=		np.transpose(lowerCAmelCase_    ,				[2, 0, 1]							)
    SCREAMING_SNAKE_CASE_      :  Any    						=		torch.from_numpy(lowerCAmelCase_							).unsqueeze(0							)
    return image





class 							lowerCAmelCase__				(			__a ):






      '''simple docstring'''

      def __init__(						self     :  List[Any]						,	lowercase_     :  UNetaDConditionModel						,	lowercase_     :  DDPMScheduler						,	lowercase_     :  VQModel						,	):




          '''simple docstring'''


          super().__init__()

          self.register_modules(
              unet=__a						,	scheduler=__a						,	movq=__a						,	)
          SCREAMING_SNAKE_CASE_      :  str    						=		2 ** (len(self.movq.config.block_out_channels) - 1)
      def _SCREAMING_SNAKE_CASE (						self     :  Any						,	lowercase_     :  Optional[int]						,	lowercase_     :  Optional[Any]						,	lowercase_     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		min(int(num_inference_steps * strength)						,	__a)

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

          return timesteps, num_inference_steps - t_start
      def _SCREAMING_SNAKE_CASE (						self     :  Tuple						,	lowercase_     :  List[Any]						,	lowercase_     :  Union[str, Any]						,	lowercase_     :  Union[str, Any]						,	lowercase_     :  Dict						,	lowercase_     :  int						,	lowercase_     :  Any						,	lowercase_     :  Optional[int]=None):




          '''simple docstring'''


          if not isinstance(__a						,	(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(__a)}')

          SCREAMING_SNAKE_CASE_      :  Tuple    						=		image.to(device=__a						,	dtype=__a)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		batch_size * num_images_per_prompt

          if image.shape[1] == 4:
              SCREAMING_SNAKE_CASE_      :  List[str]    						=		image

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

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

              SCREAMING_SNAKE_CASE_      :  Dict    						=		self.movq.config.scaling_factor * init_latents

          SCREAMING_SNAKE_CASE_      :  str    						=		torch.cat([init_latents]						,	dim=0)

          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		init_latents.shape
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		randn_tensor(__a						,	generator=__a						,	device=__a						,	dtype=__a)

          # get latents
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.scheduler.add_noise(__a						,	__a						,	__a)

          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		init_latents

          return latents
      def _SCREAMING_SNAKE_CASE (						self     :  Union[str, Any]						,	lowercase_     :  int=0):




          '''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_      :  List[Any]    						=		[
              self.unet,
              self.movq,
          ]
          for cpu_offloaded_model in models:
              if cpu_offloaded_model is not None:
                  cpu_offload(__a						,	__a)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]						,	lowercase_     :  List[Any]=0):




          '''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_      :  Any    						=		torch.device(F'cuda:{gpu_id}')

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

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

          # 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 _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          if not hasattr(self.unet						,	'''_hf_hook'''):
              return self.device
          for module in self.unet.modules():
              if (
                  hasattr(__a						,	'''_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(__a)
      def __call__(						self     :  Optional[int]						,	lowercase_     :  Union[torch.FloatTensor, List[torch.FloatTensor]]						,	lowercase_     :  Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]						,	lowercase_     :  Union[torch.FloatTensor, List[torch.FloatTensor]]						,	lowercase_     :  int = 512						,	lowercase_     :  int = 512						,	lowercase_     :  int = 100						,	lowercase_     :  float = 4.0						,	lowercase_     :  float = 0.3						,	lowercase_     :  int = 1						,	lowercase_     :  Optional[Union[torch.Generator, List[torch.Generator]]] = None						,	lowercase_     :  Optional[str] = "pil"						,	lowercase_     :  bool = True						,	):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[str]    						=		self._execution_device

          SCREAMING_SNAKE_CASE_      :  Any    						=		guidance_scale > 1.0

          if isinstance(__a						,	__a):
              SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		torch.cat(__a						,	dim=0)
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		image_embeds.shape[0]
          if isinstance(__a						,	__a):
              SCREAMING_SNAKE_CASE_      :  str    						=		torch.cat(__a						,	dim=0)

          if do_classifier_free_guidance:
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		image_embeds.repeat_interleave(__a						,	dim=0)
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		negative_image_embeds.repeat_interleave(__a						,	dim=0)

          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		torch.cat([negative_image_embeds, image_embeds]						,	dim=0).to(dtype=self.unet.dtype						,	device=__a)

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

          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		torch.cat([prepare_image(__a						,	__a						,	__a) for i in image]						,	dim=0)
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		image.to(dtype=image_embeds.dtype						,	device=__a)

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

              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		{"""image_embeds""": image_embeds}
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		self.unet(
                  sample=__a						,	timestep=__a						,	encoder_hidden_states=__a						,	added_cond_kwargs=__a						,	return_dict=__a						,	)[0]

              if do_classifier_free_guidance:
                  SCREAMING_SNAKE_CASE_      :  int    						=		noise_pred.split(latents.shape[1]						,	dim=1)
                  SCREAMING_SNAKE_CASE_      :  Dict    						=		noise_pred.chunk(2)
                  SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		variance_pred.chunk(2)
                  SCREAMING_SNAKE_CASE_      :  str    						=		noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                  SCREAMING_SNAKE_CASE_      :  Optional[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_      :  Any    						=		noise_pred.split(latents.shape[1]						,	dim=1)

              # compute the previous noisy sample x_t -> x_t-1
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		self.scheduler.step(
                  __a						,	__a						,	__a						,	generator=__a						,	)[0]

          # post-processing
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.movq.decode(__a						,	force_not_quantize=__a)["""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_      :  Tuple    						=		image * 0.5 + 0.5
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		image.clamp(0						,	1)
              SCREAMING_SNAKE_CASE_      :  str    						=		image.cpu().permute(0						,	2						,	3						,	1).float().numpy()

          if output_type == "pil":
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		self.numpy_to_pil(__a)

          if not return_dict:
              return (image,)

          return ImagePipelineOutput(images=__a)










from __future__ import annotations
def 					snake_case_						(   lowerCAmelCase_				:  int				,				lowerCAmelCase_				:  int					):
							if partitions <= 0:
														raise ValueError("""partitions must be a positive number!"""					)
							if partitions > number_of_bytes:
														raise ValueError("""partitions can not > number_of_bytes!"""					)
							__lowercase					:							Dict			=   number_of_bytes // partitions
							__lowercase					:							Union[str, Any]			=   []
							for i in range(lowerCAmelCase_					):
														__lowercase					:							str			=   i * bytes_per_partition + 1
														__lowercase					:							List[Any]			=   (
														    number_of_bytes if i == partitions - 1 else (i + 1) * bytes_per_partition
														)
														allocation_list.append(F"{start_bytes}-{end_bytes}"					)
							return allocation_list


if __name__ == "__main__":
	import doctest

	doctest.testmod()