




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


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

A_      =    '''
    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  UpperCAmelCase__	(snake_case__							: str		,       snake_case__							: Optional[int]		,       snake_case__							: Dict=8   ):
  """simple docstring"""

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


def  UpperCAmelCase__	(snake_case__							: List[str]		,       snake_case__							: List[Any]=5_12		,       snake_case__							: Dict=5_12   ):
  """simple docstring"""

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






class  lowercase(					__a			):







 '''simple docstring'''





 def __init__(    self:		Optional[Any],				a_:		UNetaDConditionModel,				a_:		DDPMScheduler,				a_:		VQModel,				):




   '''simple docstring'''



   super().__init__()

   self.register_modules(
       unet=a_,				scheduler=a_,				movq=a_,				)
   _snake_case							:		Optional[Any]								=  2 ** (len(self.movq.config.block_out_channels		) - 1)


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Dict,				a_:		Any,				a_:		Optional[int]		):




   '''simple docstring'''



   _snake_case							:		Any								=  min(int(num_inference_steps * strength		),				a_		)

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

   return timesteps, num_inference_steps - t_start


 def 			UpperCamelCase_       (    self:		str,				a_:		Optional[int],				a_:		str,				a_:		Tuple,				a_:		Optional[int],				a_:		Optional[Any],				a_:		Optional[int],				a_:		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_		)}"		)

   _snake_case							:		List[Any]								=  image.to(device=a_,				dtype=a_		)

   _snake_case							:		str								=  batch_size * num_images_per_prompt

   if image.shape[1] == 4:
     _snake_case							:		Tuple								=  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_		):
       _snake_case							:		str								=  [
           self.movq.encode(image[i : i + 1]		).latent_dist.sample(generator[i]		) for i in range(a_		)
       ]
       _snake_case							:		Optional[int]								=  torch.cat(a_,				dim=0		)
     else:
       _snake_case							:		int								=  self.movq.encode(a_		).latent_dist.sample(a_		)

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

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

   _snake_case							:		Optional[int]								=  init_latents.shape
   _snake_case							:		Dict								=  randn_tensor(a_,				generator=a_,				device=a_,				dtype=a_		)

   # get latents
   _snake_case							:		Tuple								=  self.scheduler.add_noise(a_,				a_,				a_		)

   _snake_case							:		Union[str, Any]								=  init_latents

   return latents


 def 			UpperCamelCase_       (    self:		Union[str, Any],				a_:		Optional[int]=0		):




   '''simple docstring'''



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

   _snake_case							:		str								=  torch.device(f"cuda:{gpu_id}"		)

   _snake_case							:		Union[str, Any]								=  [
       self.unet,
       self.movq,
   ]
   for cpu_offloaded_model in models:
     if cpu_offloaded_model is not None:
       cpu_offload(a_,				a_		)


 def 			UpperCamelCase_       (    self:		str,				a_:		int=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."""		)

   _snake_case							:		List[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)

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

   # We'll offload the last model manually.
   _snake_case							:		List[Any]								=  hook


 @property
 # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
 def 			UpperCamelCase_       (    self:		str		):




   '''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:		Dict,				a_:		Union[torch.FloatTensor, List[torch.FloatTensor]],				a_:		Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]],				a_:		Union[torch.FloatTensor, List[torch.FloatTensor]],				a_:		int = 512,				a_:		int = 512,				a_:		int = 100,				a_:		float = 4.0,				a_:		float = 0.3,				a_:		int = 1,				a_:		Optional[Union[torch.Generator, List[torch.Generator]]] = None,				a_:		Optional[str] = "pil",				a_:		bool = True,				):




   '''simple docstring'''



   _snake_case							:		Optional[int]								=  self._execution_device

   _snake_case							:		str								=  guidance_scale > 1.0

   if isinstance(a_,				a_		):
     _snake_case							:		Optional[int]								=  torch.cat(a_,				dim=0		)
   _snake_case							:		Optional[Any]								=  image_embeds.shape[0]
   if isinstance(a_,				a_		):
     _snake_case							:		str								=  torch.cat(a_,				dim=0		)

   if do_classifier_free_guidance:
     _snake_case							:		Optional[Any]								=  image_embeds.repeat_interleave(a_,				dim=0		)
     _snake_case							:		Dict								=  negative_image_embeds.repeat_interleave(a_,				dim=0		)

   _snake_case							:		Optional[int]								=  torch.cat([negative_image_embeds, image_embeds],				dim=0		).to(dtype=self.unet.dtype,				device=a_		)

   if not isinstance(a_,				a_		):
     _snake_case							:		Dict								=  [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"		)

   _snake_case							:		Union[str, Any]								=  torch.cat([prepare_image(a_,				a_,				a_		) for i in image],				dim=0		)
   _snake_case							:		Union[str, Any]								=  image.to(dtype=image_embeds.dtype,				device=a_		)

   _snake_case							:		Tuple								=  self.movq.encode(a_		)["""latents"""]
   _snake_case							:		List[Any]								=  latents.repeat_interleave(a_,				dim=0		)
   self.scheduler.set_timesteps(a_,				device=a_		)
   _snake_case		, _snake_case							:		Dict								=  self.get_timesteps(a_,				a_,				a_		)
   _snake_case							:		List[str]								=  timesteps[:1].repeat(batch_size * num_images_per_prompt		)
   _snake_case		, _snake_case							:		str								=  downscale_height_and_width(a_,				a_,				self.movq_scale_factor		)
   _snake_case							:		Union[str, 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
     _snake_case							:		Dict								=  torch.cat([latents] * 2		) if do_classifier_free_guidance else latents

     _snake_case							:		Union[str, Any]								=  {"""image_embeds""": image_embeds}
     _snake_case							:		Any								=  self.unet(
         sample=a_,				timestep=a_,				encoder_hidden_states=a_,				added_cond_kwargs=a_,				return_dict=a_,				)[0]

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

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

   # post-processing
   _snake_case							:		Optional[int]								=  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"]:
     _snake_case							:		List[Any]								=  image * 0.5 + 0.5
     _snake_case							:		Optional[Any]								=  image.clamp(0,				1		)
     _snake_case							:		str								=  image.cpu().permute(0,				2,				3,				1		).float().numpy()

   if output_type == "pil":
     _snake_case							:		Optional[Any]								=  self.numpy_to_pil(a_		)

   if not return_dict:
     return (image,)

   return ImagePipelineOutput(images=a_		)








"""simple docstring"""


from collections.abc import Generator
from math import sin


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) != 32:
    raise ValueError("""Input must be of length 32"""   )

  _snake_case							:		Optional[int]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian += string_aa[8 * i : 8 * i + 8]
  return little_endian


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[Any]								=  format(snake_case__		,       """08x"""   )[-8:]
  _snake_case							:		Optional[Any]								=  B""""""
  for i in [3, 2, 1, 0]:
    little_endian_hex += hex_rep[2 * i : 2 * i + 2].encode("""utf-8"""   )
  return little_endian_hex


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Union[str, Any]								=  B""""""
  for char in message:
    bit_string += format(snake_case__		,       """08b"""   ).encode("""utf-8"""   )
  _snake_case							:		List[Any]								=  format(len(snake_case__   )		,       """064b"""   ).encode("""utf-8"""   )

  # Pad bit_string to a multiple of 512 chars
  bit_string += b"1"
  while len(snake_case__   ) % 5_12 != 4_48:
    bit_string += b"0"
  bit_string += to_little_endian(start_len[32:]   ) + to_little_endian(start_len[:32]   )

  return bit_string


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  if len(snake_case__   ) % 5_12 != 0:
    raise ValueError("""Input must have length that's a multiple of 512"""   )

  for pos in range(0		,       len(snake_case__   )		,       5_12   ):
    _snake_case							:		List[str]								=  bit_string[pos : pos + 5_12]
    _snake_case							:		List[str]								=  []
    for i in range(0		,       5_12		,       32   ):
      block_words.append(int(to_little_endian(block[i : i + 32]   )		,       2   )   )
    yield block_words


def  UpperCAmelCase__	(snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )

  _snake_case							:		Optional[int]								=  format(snake_case__		,       """032b"""   )
  _snake_case							:		str								=  """"""
  for c in i_str:
    new_str += "1" if c == "0" else "0"
  return int(snake_case__		,       2   )


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  return (a + b) % 2**32


def  UpperCAmelCase__	(snake_case__							: int		,       snake_case__							: int   ):
  """simple docstring"""

  if i < 0:
    raise ValueError("""Input must be non-negative"""   )
  if shift < 0:
    raise ValueError("""Shift must be non-negative"""   )
  return ((i << shift) ^ (i >> (32 - shift))) % 2**32


def  UpperCAmelCase__	(snake_case__							: bytes   ):
  """simple docstring"""

  _snake_case							:		Any								=  preprocess(snake_case__   )

  _snake_case							:		Optional[Any]								=  [int(2**32 * abs(sin(i + 1   )   )   ) for i in range(64   )]

  # Starting states
  _snake_case							:		Union[str, Any]								=  0x6745_2301
  _snake_case							:		List[Any]								=  0xEFCD_AB89
  _snake_case							:		Optional[Any]								=  0x98BA_DCFE
  _snake_case							:		Optional[int]								=  0x1032_5476

  _snake_case							:		Tuple								=  [
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      7,
      12,
      17,
      22,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      5,
      9,
      14,
      20,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      4,
      11,
      16,
      23,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
      6,
      10,
      15,
      21,
  ]

  # Process bit string in chunks, each with 16 32-char words
  for block_words in get_block_words(snake_case__   ):
    _snake_case							:		Tuple								=  aa
    _snake_case							:		str								=  ba
    _snake_case							:		int								=  ca
    _snake_case							:		Dict								=  da

    # Hash current chunk
    for i in range(64   ):
      if i <= 15:
        # f = (b & c) | (not_32(b) & d)     # Alternate definition for f
        _snake_case							:		int								=  d ^ (b & (c ^ d))
        _snake_case							:		Dict								=  i
      elif i <= 31:
        # f = (d & b) | (not_32(d) & c)     # Alternate definition for f
        _snake_case							:		Tuple								=  c ^ (d & (b ^ c))
        _snake_case							:		int								=  (5 * i + 1) % 16
      elif i <= 47:
        _snake_case							:		List[Any]								=  b ^ c ^ d
        _snake_case							:		Union[str, Any]								=  (3 * i + 5) % 16
      else:
        _snake_case							:		Tuple								=  c ^ (b | not_aa(snake_case__   ))
        _snake_case							:		Optional[int]								=  (7 * i) % 16
      _snake_case							:		Dict								=  (f + a + added_consts[i] + block_words[g]) % 2**32
      _snake_case							:		List[str]								=  d
      _snake_case							:		List[Any]								=  c
      _snake_case							:		str								=  b
      _snake_case							:		List[str]								=  sum_aa(snake_case__		,       left_rotate_aa(snake_case__		,       shift_amounts[i]   )   )

    # Add hashed chunk to running total
    _snake_case							:		Union[str, Any]								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		str								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		Any								=  sum_aa(snake_case__		,       snake_case__   )
    _snake_case							:		List[str]								=  sum_aa(snake_case__		,       snake_case__   )

  _snake_case							:		Any								=  reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   ) + reformat_hex(snake_case__   )
  return digest


if __name__ == "__main__":
     import doctest

     doctest.testmod()


