




from typing import List, Optional, Union

import torch

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__					:  Union[str, Any]      							=				logging.get_logger(__name__)  # pylint: disable=invalid-name

lowerCamelCase__					:  Dict      							=				'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n        >>> pipe_prior.to("cuda")\n        >>> prompt = "red cat, 4k photo"\n        >>> out = pipe_prior(prompt)\n        >>> image_emb = out.image_embeds\n        >>> zero_image_emb = out.negative_image_embeds\n        >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n        >>> pipe.to("cuda")\n        >>> image = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=50,\n        ... ).images\n        >>> image[0].save("cat.png")\n        ```\n'

def    UpperCAmelCase_				( __UpperCAmelCase		:      Optional[int]     ,     __UpperCAmelCase		:      int     ,     __UpperCAmelCase		:      Any=8				)   ->					Dict:
      SCREAMING_SNAKE_CASE_      		=     height // scale_factor**2
      if height % scale_factor**2 != 0:
            new_height += 1
      SCREAMING_SNAKE_CASE_      		=     width // scale_factor**2
      if width % scale_factor**2 != 0:
            new_width += 1
      return new_height * scale_factor, new_width * scale_factor





class 			lowerCamelCase_				( _SCREAMING_SNAKE_CASE   ):


 '''simple docstring'''







 def __init__(				self    :						Dict							,							_lowerCAmelCase    :						UNetaDConditionModel							,							_lowerCAmelCase    :						DDPMScheduler							,							_lowerCAmelCase    :						VQModel							,							):
       super().__init__()

       self.register_modules(
           unet=_lowerCAmelCase							,							scheduler=_lowerCAmelCase							,							movq=_lowerCAmelCase							,							)
       SCREAMING_SNAKE_CASE_      		=     2 ** (len(self.movq.config.block_out_channels		) - 1)



 def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						str							,							_lowerCAmelCase    :						Optional[int]							,							_lowerCAmelCase    :						Dict							,							_lowerCAmelCase    :						Optional[int]							,							_lowerCAmelCase    :						List[str]							,							_lowerCAmelCase    :						List[Any]		):
       if latents is None:
             SCREAMING_SNAKE_CASE_      		=     randn_tensor(_lowerCAmelCase							,							generator=_lowerCAmelCase							,							device=_lowerCAmelCase							,							dtype=_lowerCAmelCase		)
       else:
             if latents.shape != shape:
                   raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"		)
             SCREAMING_SNAKE_CASE_      		=     latents.to(_lowerCAmelCase		)

       SCREAMING_SNAKE_CASE_      		=     latents * scheduler.init_noise_sigma
       return latents



 def  lowerCAmelCase_    (				self    :						Optional[Any]							,							_lowerCAmelCase    :						str=0		):
       if is_accelerate_available():
             from accelerate import cpu_offload
       else:
             raise ImportError('Please install accelerate via `pip install accelerate`'		)

       SCREAMING_SNAKE_CASE_      		=     torch.device(F"cuda:{gpu_id}"		)

       SCREAMING_SNAKE_CASE_      		=     [
           self.unet,
           self.movq,
       ]
       for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                   cpu_offload(_lowerCAmelCase							,							_lowerCAmelCase		)



 def  lowerCAmelCase_    (				self    :						List[str]							,							_lowerCAmelCase    :						Any=0		):
       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_      		=     torch.device(F"cuda:{gpu_id}"		)

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

       SCREAMING_SNAKE_CASE_      		=     None
       for cpu_offloaded_model in [self.unet, self.movq]:
             SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     cpu_offload_with_hook(_lowerCAmelCase							,							_lowerCAmelCase							,							prev_module_hook=_lowerCAmelCase		)

       # We'll offload the last model manually.
       SCREAMING_SNAKE_CASE_      		=     hook



 @property
 # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
 def  lowerCAmelCase_    (				self    :						int		):
       if not hasattr(self.unet							,							'_hf_hook'		):
             return self.device
       for module in self.unet.modules():
             if (
                 hasattr(_lowerCAmelCase							,							'_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(_lowerCAmelCase		)
 def __call__(				self    :						Any							,							_lowerCAmelCase    :						Union[torch.FloatTensor, List[torch.FloatTensor]]							,							_lowerCAmelCase    :						Union[torch.FloatTensor, List[torch.FloatTensor]]							,							_lowerCAmelCase    :						int = 512							,							_lowerCAmelCase    :						int = 512							,							_lowerCAmelCase    :						int = 100							,							_lowerCAmelCase    :						float = 4.0							,							_lowerCAmelCase    :						int = 1							,							_lowerCAmelCase    :						Optional[Union[torch.Generator, List[torch.Generator]]] = None							,							_lowerCAmelCase    :						Optional[torch.FloatTensor] = None							,							_lowerCAmelCase    :						Optional[str] = "pil"							,							_lowerCAmelCase    :						bool = True							,							):
       SCREAMING_SNAKE_CASE_      		=     self._execution_device

       SCREAMING_SNAKE_CASE_      		=     guidance_scale > 1.0

       if isinstance(_lowerCAmelCase							,							_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     torch.cat(_lowerCAmelCase							,							dim=0		)
       SCREAMING_SNAKE_CASE_      		=     image_embeds.shape[0] * num_images_per_prompt
       if isinstance(_lowerCAmelCase							,							_lowerCAmelCase		):
             SCREAMING_SNAKE_CASE_      		=     torch.cat(_lowerCAmelCase							,							dim=0		)

       if do_classifier_free_guidance:
             SCREAMING_SNAKE_CASE_      		=     image_embeds.repeat_interleave(_lowerCAmelCase							,							dim=0		)
             SCREAMING_SNAKE_CASE_      		=     negative_image_embeds.repeat_interleave(_lowerCAmelCase							,							dim=0		)

       SCREAMING_SNAKE_CASE_      		=     torch.cat([negative_image_embeds, image_embeds]							,							dim=0		).to(dtype=self.unet.dtype							,							device=_lowerCAmelCase		)

       self.scheduler.set_timesteps(_lowerCAmelCase							,							device=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.scheduler.timesteps

       SCREAMING_SNAKE_CASE_      		=     self.unet.config.in_channels

       SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     downscale_height_and_width(_lowerCAmelCase							,							_lowerCAmelCase							,							self.movq_scale_factor		)

       # create initial latent
       SCREAMING_SNAKE_CASE_      		=     self.prepare_latents(
           (batch_size, num_channels_latents, height, width)							,							image_embeds.dtype							,							_lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase							,							self.scheduler							,							)

       for i, t in enumerate(self.progress_bar(_lowerCAmelCase		)		):
             # expand the latents if we are doing classifier free guidance
             SCREAMING_SNAKE_CASE_      		=     torch.cat([latents] * 2		) if do_classifier_free_guidance else latents

             SCREAMING_SNAKE_CASE_      		=     {'image_embeds': image_embeds}
             SCREAMING_SNAKE_CASE_      		=     self.unet(
                 sample=_lowerCAmelCase							,							timestep=_lowerCAmelCase							,							encoder_hidden_states=_lowerCAmelCase							,							added_cond_kwargs=_lowerCAmelCase							,							return_dict=_lowerCAmelCase							,							)[0]

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

             # compute the previous noisy sample x_t -> x_t-1
             SCREAMING_SNAKE_CASE_      		=     self.scheduler.step(
                 _lowerCAmelCase							,							_lowerCAmelCase							,							_lowerCAmelCase							,							generator=_lowerCAmelCase							,							)[0]
       # post-processing
       SCREAMING_SNAKE_CASE_      		=     self.movq.decode(_lowerCAmelCase							,							force_not_quantize=_lowerCAmelCase		)['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_      		=     image * 0.5 + 0.5
             SCREAMING_SNAKE_CASE_      		=     image.clamp(0							,							1		)
             SCREAMING_SNAKE_CASE_      		=     image.cpu().permute(0							,							2							,							3							,							1		).float().numpy()

       if output_type == "pil":
             SCREAMING_SNAKE_CASE_      		=     self.numpy_to_pil(_lowerCAmelCase		)

       if not return_dict:
             return (image,)

       return ImagePipelineOutput(images=_lowerCAmelCase		)





'''simple docstring'''


from collections.abc import Generator
from math import sin
def 						snake_case_       (UpperCamelCase			:    bytes ):





							'''simple docstring'''


							if len(UpperCamelCase ) != 32:
														raise ValueError('''Input must be of length 32''' )

							_a      	=							B''''''
							for i in [3, 2, 1, 0]:
														little_endian += string_aa[8 * i : 8 * i + 8]
							return little_endian
def 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


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

							_a      	=							format(UpperCamelCase					,		'''08x''' )[-8:]
							_a      	=							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 						snake_case_       (UpperCamelCase			:    bytes ):





							'''simple docstring'''


							_a      	=							B''''''
							for char in message:
														bit_string += format(UpperCamelCase					,		'''08b''' ).encode('''utf-8''' )
							_a      	=							format(len(UpperCamelCase )					,		'''064b''' ).encode('''utf-8''' )

							# Pad bit_string to a multiple of 512 chars
							bit_string += b"1"
							while len(UpperCamelCase ) % 512 != 448:
														bit_string += b"0"
							bit_string += to_little_endian(start_len[32:] ) + to_little_endian(start_len[:32] )

							return bit_string
def 						snake_case_       (UpperCamelCase			:    bytes ):





							'''simple docstring'''


							if len(UpperCamelCase ) % 512 != 0:
														raise ValueError('''Input must have length that\'s a multiple of 512''' )

							for pos in range(0					,		len(UpperCamelCase )					,		512 ):
														_a      	=							bit_string[pos : pos + 512]
														_a      	=							[]
														for i in range(0					,		512					,		32 ):
																					block_words.append(int(to_little_endian(block[i : i + 32] )					,		2 ) )
														yield block_words
def 						snake_case_       (UpperCamelCase			:    int ):





							'''simple docstring'''


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

							_a      	=							format(UpperCamelCase					,		'''032b''' )
							_a      	=							''''''
							for c in i_str:
														new_str += "1" if c == "0" else "0"
							return int(UpperCamelCase					,		2 )
def 						snake_case_       (UpperCamelCase			:    int					,		UpperCamelCase			:    int ):





							'''simple docstring'''


							return (a + b) % 2**32
def 						snake_case_       (UpperCamelCase			:    int					,		UpperCamelCase			:    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 						snake_case_       (UpperCamelCase			:    bytes ):





							'''simple docstring'''


							_a      	=							preprocess(UpperCamelCase )

							_a      	=							[int(2**32 * abs(sin(i + 1 ) ) ) for i in range(64 )]

							# Starting states
							_a      	=							0X67452301
							_a      	=							0Xefcdab89
							_a      	=							0X98badcfe
							_a      	=							0X10325476

							_a      	=							[
							    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(UpperCamelCase ):
														_a      	=							aa
														_a      	=							ba
														_a      	=							ca
														_a      	=							da

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

														# Add hashed chunk to running total
														_a      	=							sum_aa(UpperCamelCase					,		UpperCamelCase )
														_a      	=							sum_aa(UpperCamelCase					,		UpperCamelCase )
														_a      	=							sum_aa(UpperCamelCase					,		UpperCamelCase )
														_a      	=							sum_aa(UpperCamelCase					,		UpperCamelCase )

							_a      	=							reformat_hex(UpperCamelCase ) + reformat_hex(UpperCamelCase ) + reformat_hex(UpperCamelCase ) + reformat_hex(UpperCamelCase )
							return digest


if __name__ == "__main__":
				import doctest

				doctest.testmod()

