
"""simple docstring"""
import unittest

import numpy as np
import torch
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()




class    _snake_case  (						_lowercase ,				unittest.TestCase       ):
							SCREAMING_SNAKE_CASE		     =						KandinskyPriorPipeline
							SCREAMING_SNAKE_CASE		     =						['''prompt''']
							SCREAMING_SNAKE_CASE		     =						['''prompt''', '''negative_prompt''']
							SCREAMING_SNAKE_CASE		     =						[
							    '''num_images_per_prompt''',
							    '''generator''',
							    '''num_inference_steps''',
							    '''latents''',
							    '''negative_prompt''',
							    '''guidance_scale''',
							    '''output_type''',
							    '''return_dict''',
							]
							SCREAMING_SNAKE_CASE		     =						False






							@property
							def 							__lowercase  (					self						:			Optional[int]    ):






												"""simple docstring"""



												return 3_2






							@property
							def 							__lowercase  (					self						:			int    ):






												"""simple docstring"""



												return 3_2






							@property
							def 							__lowercase  (					self						:			Optional[Any]    ):






												"""simple docstring"""



												return self.time_input_dim






							@property
							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												return self.time_input_dim * 4






							@property
							def 							__lowercase  (					self						:			Dict    ):






												"""simple docstring"""



												return 1_0_0






							@property
							def 							__lowercase  (					self						:			Dict    ):






												"""simple docstring"""



												__a:						List[Any]		    =					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )
												return tokenizer






							@property
							def 							__lowercase  (					self						:			Optional[int]    ):






												"""simple docstring"""



												torch.manual_seed(0    )
												__a:						Any		    =					CLIPTextConfig(
												    bos_token_id=0						, eos_token_id=2						, hidden_size=self.text_embedder_hidden_size						, projection_dim=self.text_embedder_hidden_size						, intermediate_size=3_7						, layer_norm_eps=1e-05						, num_attention_heads=4						, num_hidden_layers=5						, pad_token_id=1						, vocab_size=1_0_0_0						, )
												return CLIPTextModelWithProjection(snake_case__    )






							@property
							def 							__lowercase  (					self						:			Optional[int]    ):






												"""simple docstring"""



												torch.manual_seed(0    )

												__a:						int		    =					{
												    """num_attention_heads""": 2,
												    """attention_head_dim""": 1_2,
												    """embedding_dim""": self.text_embedder_hidden_size,
												    """num_layers""": 1,
												}

												__a:						List[str]		    =					PriorTransformer(**snake_case__    )
												# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
												__a:						Tuple		    =					nn.Parameter(torch.ones(model.clip_std.shape    )    )
												return model






							@property
							def 							__lowercase  (					self						:			Union[str, Any]    ):






												"""simple docstring"""



												torch.manual_seed(0    )
												__a:						str		    =					CLIPVisionConfig(
												    hidden_size=self.text_embedder_hidden_size						, image_size=2_2_4						, projection_dim=self.text_embedder_hidden_size						, intermediate_size=3_7						, num_attention_heads=4						, num_channels=3						, num_hidden_layers=5						, patch_size=1_4						, )

												__a:						Dict		    =					CLIPVisionModelWithProjection(snake_case__    )
												return model






							@property
							def 							__lowercase  (					self						:			List[Any]    ):






												"""simple docstring"""



												__a:						Any		    =					CLIPImageProcessor(
												    crop_size=2_2_4						, do_center_crop=snake_case__						, do_normalize=snake_case__						, do_resize=snake_case__						, image_mean=[0.48_145_466, 0.4_578_275, 0.40_821_073]						, image_std=[0.26_862_954, 0.26_130_258, 0.27_577_711]						, resample=3						, size=2_2_4						, )

												return image_processor






							def 							__lowercase  (					self						:			Union[str, Any]    ):






												"""simple docstring"""



												__a:						Tuple		    =					self.dummy_prior
												__a:						Dict		    =					self.dummy_image_encoder
												__a:						Optional[int]		    =					self.dummy_text_encoder
												__a:						List[str]		    =					self.dummy_tokenizer
												__a:						Any		    =					self.dummy_image_processor

												__a:						List[str]		    =					UnCLIPScheduler(
												    variance_type="""fixed_small_log"""						, prediction_type="""sample"""						, num_train_timesteps=1_0_0_0						, clip_sample=snake_case__						, clip_sample_range=10.0						, )

												__a:						Optional[Any]		    =					{
												    """prior""": prior,
												    """image_encoder""": image_encoder,
												    """text_encoder""": text_encoder,
												    """tokenizer""": tokenizer,
												    """scheduler""": scheduler,
												    """image_processor""": image_processor,
												}

												return components






							def 							__lowercase  (					self						:			List[Any]						, snake_case__						:			int						, snake_case__						:			int=0    ):






												"""simple docstring"""



												if str(snake_case__    ).startswith("""mps"""    ):
																	__a:						Dict		    =					torch.manual_seed(snake_case__    )
												else:
																	__a:						Dict		    =					torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
												__a:						Optional[int]		    =					{
												    """prompt""": """horse""",
												    """generator""": generator,
												    """guidance_scale""": 4.0,
												    """num_inference_steps""": 2,
												    """output_type""": """np""",
												}
												return inputs






							def 							__lowercase  (					self						:			int    ):






												"""simple docstring"""



												__a:						Tuple		    =					"""cpu"""

												__a:						List[Any]		    =					self.get_dummy_components()

												__a:						str		    =					self.pipeline_class(**snake_case__    )
												__a:						Any		    =					pipe.to(snake_case__    )

												pipe.set_progress_bar_config(disable=snake_case__    )

												__a:						Dict		    =					pipe(**self.get_dummy_inputs(snake_case__    )    )
												__a:						Optional[Any]		    =					output.image_embeds

												__a:						Tuple		    =					pipe(
												    **self.get_dummy_inputs(snake_case__    )						, return_dict=snake_case__						, )[0]

												__a:						List[Any]		    =					image[0, -1_0:]
												__a:						Dict		    =					image_from_tuple[0, -1_0:]

												assert image.shape == (1, 3_2)

												__a:						Dict		    =					np.array(
												    [-0.0_532, 1.7_120, 0.3_656, -1.0_852, -0.8_946, -1.1_756, 0.4_348, 0.2_482, 0.5_146, -0.1_156]    )

												assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-2
												assert np.abs(image_from_tuple_slice.flatten() - expected_slice    ).max() < 1e-2






							@skip_mps
							def 							__lowercase  (					self						:			str    ):






												"""simple docstring"""



												__a:						int		    =					torch_device == """cpu"""
												__a:						Optional[int]		    =					True
												__a:						Optional[Any]		    =					False

												self._test_inference_batch_single_identical(
												    test_max_difference=snake_case__						, relax_max_difference=snake_case__						, test_mean_pixel_difference=snake_case__						, )






							@skip_mps
							def 							__lowercase  (					self						:			Union[str, Any]    ):






												"""simple docstring"""



												__a:						Union[str, Any]		    =					torch_device == """cpu"""
												__a:						int		    =					False

												self._test_attention_slicing_forward_pass(
												    test_max_difference=snake_case__						, test_mean_pixel_difference=snake_case__						, )


"""simple docstring"""
lowercase		:						str =					{
    '0000': '0',
    '0001': '1',
    '0010': '2',
    '0011': '3',
    '0100': '4',
    '0101': '5',
    '0110': '6',
    '0111': '7',
    '1000': '8',
    '1001': '9',
    '1010': 'a',
    '1011': 'b',
    '1100': 'c',
    '1101': 'd',
    '1110': 'e',
    '1111': 'f',
}


def     lowerCamelCase_    (	lowerCamelCase_ )     ->			str:


					'''simple docstring'''
					__a:						Optional[int]		    =					str(lowerCamelCase_ ).strip()

					# Exceptions
					if not binary_str:
										raise ValueError("""Empty string was passed to the function""" )
					__a:						List[Any]		    =					binary_str[0] == """-"""
					__a:						List[str]		    =					binary_str[1:] if is_negative else binary_str
					if not all(char in """01""" for char in binary_str ):
										raise ValueError("""Non-binary value was passed to the function""" )

					__a:						Any		    =					(
					    """0""" * (4 * (divmod(len(lowerCamelCase_ )	,				4 )[0] + 1) - len(lowerCamelCase_ )) + binary_str
					)

					__a:						int		    =					[]
					for x in range(0	,				len(lowerCamelCase_ )	,				4 ):
										hexadecimal.append(BITS_TO_HEX[binary_str[x : x + 4]] )
					__a:						Tuple		    =					"""0x""" + """""".join(lowerCamelCase_ )

					return "-" + hexadecimal_str if is_negative else hexadecimal_str


if __name__ == "__main__":
			from doctest import testmod

			testmod()
