






import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModel

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEImgaImgPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import floats_tensor, load_image, load_numpy, slow
from diffusers.utils.testing_utils import require_torch_gpu, torch_device

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
class 				A_     (    SCREAMING_SNAKE_CASE_			, unittest.TestCase      ):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE				:      Optional[Any]			=       ShapEImgaImgPipeline
 _SCREAMING_SNAKE_CASE				:      Tuple			=       ["image"]
 _SCREAMING_SNAKE_CASE				:      int			=       ["image"]
 _SCREAMING_SNAKE_CASE				:      str			=       [
     "num_images_per_prompt",
     "num_inference_steps",
     "generator",
     "latents",
     "guidance_scale",
     "frame_size",
     "output_type",
     "return_dict",
 ]
 _SCREAMING_SNAKE_CASE				:      Union[str, Any]			=       False


 @property
 def 			snake_case__					(						self)			->		Any:

     """simple docstring"""



     return 32


 @property
 def 			snake_case__					(						self)			->		Dict:

     """simple docstring"""



     return 32


 @property
 def 			snake_case__					(						self)			->		Optional[Any]:

     """simple docstring"""



     return self.time_input_dim * 4


 @property
 def 			snake_case__					(						self)			->		Optional[Any]:

     """simple docstring"""



     return 8


 @property
 def 			snake_case__					(						self)			->		Dict:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase					:   Union[str, Any]      	=					CLIPVisionConfig(
         hidden_size=self.text_embedder_hidden_size				,	image_size=64				,	projection_dim=self.text_embedder_hidden_size				,	intermediate_size=37				,	num_attention_heads=4				,	num_channels=3				,	num_hidden_layers=5				,	patch_size=1				,	)

     _UpperCAmelCase					:   int      	=					CLIPVisionModel(snake_case__)
     return model


 @property
 def 			snake_case__					(						self)			->		Any:

     """simple docstring"""



     _UpperCAmelCase					:   Any      	=					CLIPImageProcessor(
         crop_size=224				,	do_center_crop=snake_case__				,	do_normalize=snake_case__				,	do_resize=snake_case__				,	image_mean=[0.48145466, 0.4578275, 0.40821073]				,	image_std=[0.26862954, 0.26130258, 0.27577711]				,	resample=3				,	size=224				,	)

     return image_processor


 @property
 def 			snake_case__					(						self)			->		Any:

     """simple docstring"""



     torch.manual_seed(0)

     _UpperCAmelCase					:   List[Any]      	=					{
         '''num_attention_heads''': 2,
         '''attention_head_dim''': 16,
         '''embedding_dim''': self.time_input_dim,
         '''num_embeddings''': 32,
         '''embedding_proj_dim''': self.text_embedder_hidden_size,
         '''time_embed_dim''': self.time_embed_dim,
         '''num_layers''': 1,
         '''clip_embed_dim''': self.time_input_dim * 2,
         '''additional_embeddings''': 0,
         '''time_embed_act_fn''': '''gelu''',
         '''norm_in_type''': '''layer''',
         '''embedding_proj_norm_type''': '''layer''',
         '''encoder_hid_proj_type''': None,
         '''added_emb_type''': None,
     }

     _UpperCAmelCase					:   List[Any]      	=					PriorTransformer(**snake_case__)
     return model


 @property
 def 			snake_case__					(						self)			->		Optional[int]:

     """simple docstring"""



     torch.manual_seed(0)

     _UpperCAmelCase					:   Union[str, Any]      	=					{
         '''param_shapes''': (
             (self.renderer_dim, 93),
             (self.renderer_dim, 8),
             (self.renderer_dim, 8),
             (self.renderer_dim, 8),
         ),
         '''d_latent''': self.time_input_dim,
         '''d_hidden''': self.renderer_dim,
         '''n_output''': 12,
         '''background''': (
             0.1,
             0.1,
             0.1,
         ),
     }
     _UpperCAmelCase					:   Optional[Any]      	=					ShapERenderer(**snake_case__)
     return model


 def 			snake_case__					(						self)			->		str:

     """simple docstring"""



     _UpperCAmelCase					:   Tuple      	=					self.dummy_prior
     _UpperCAmelCase					:   Optional[Any]      	=					self.dummy_image_encoder
     _UpperCAmelCase					:   Optional[int]      	=					self.dummy_image_processor
     _UpperCAmelCase					:   Union[str, Any]      	=					self.dummy_renderer

     _UpperCAmelCase					:   Optional[int]      	=					HeunDiscreteScheduler(
         beta_schedule='''exp'''				,	num_train_timesteps=1024				,	prediction_type='''sample'''				,	use_karras_sigmas=snake_case__				,	clip_sample=snake_case__				,	clip_sample_range=1.0				,	)
     _UpperCAmelCase					:   Tuple      	=					{
         '''prior''': prior,
         '''image_encoder''': image_encoder,
         '''image_processor''': image_processor,
         '''renderer''': renderer,
         '''scheduler''': scheduler,
     }

     return components


 def 			snake_case__					(						self				,	_A				,	_A=0)			->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase					:   Union[str, Any]      	=					floats_tensor((1, 3, 64, 64)				,	rng=random.Random(snake_case__)).to(snake_case__)

     if str(snake_case__).startswith('''mps'''):
         _UpperCAmelCase					:   Optional[int]      	=					torch.manual_seed(snake_case__)
     else:
         _UpperCAmelCase					:   Any      	=					torch.Generator(device=snake_case__).manual_seed(snake_case__)
     _UpperCAmelCase					:   Optional[int]      	=					{
         '''image''': input_image,
         '''generator''': generator,
         '''num_inference_steps''': 1,
         '''frame_size''': 32,
         '''output_type''': '''np''',
     }
     return inputs


 def 			snake_case__					(						self)			->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase					:   str      	=					'''cpu'''

     _UpperCAmelCase					:   Union[str, Any]      	=					self.get_dummy_components()

     _UpperCAmelCase					:   Tuple      	=					self.pipeline_class(**snake_case__)
     _UpperCAmelCase					:   Optional[Any]      	=					pipe.to(snake_case__)

     pipe.set_progress_bar_config(disable=snake_case__)

     _UpperCAmelCase					:   Optional[int]      	=					pipe(**self.get_dummy_inputs(snake_case__))
     _UpperCAmelCase					:   Tuple      	=					output.images[0]
     _UpperCAmelCase					:   List[str]      	=					image[0, -3:, -3:, -1]

     assert image.shape == (20, 32, 32, 3)

     _UpperCAmelCase					:   str      	=					np.array(
         [
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
             0.00039216,
         ])

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


 def 			snake_case__					(						self)			->		Optional[Any]:

     """simple docstring"""



     self._test_inference_batch_consistent(batch_sizes=[1, 2])


 def 			snake_case__					(						self)			->		Tuple:

     """simple docstring"""



     _UpperCAmelCase					:   List[str]      	=					torch_device == '''cpu'''
     _UpperCAmelCase					:   Any      	=					True
     self._test_inference_batch_single_identical(
         batch_size=2				,	test_max_difference=snake_case__				,	relax_max_difference=snake_case__				,	)


 def 			snake_case__					(						self)			->		Tuple:

     """simple docstring"""



     _UpperCAmelCase					:   str      	=					self.get_dummy_components()
     _UpperCAmelCase					:   int      	=					self.pipeline_class(**snake_case__)
     _UpperCAmelCase					:   Optional[int]      	=					pipe.to(snake_case__)
     pipe.set_progress_bar_config(disable=snake_case__)

     _UpperCAmelCase					:   List[str]      	=					1
     _UpperCAmelCase					:   str      	=					2

     _UpperCAmelCase					:   str      	=					self.get_dummy_inputs(snake_case__)

     for key in inputs.keys():
         if key in self.batch_params:
             _UpperCAmelCase					:   List[str]      	=					batch_size * [inputs[key]]

     _UpperCAmelCase					:   Any      	=					pipe(**snake_case__				,	num_images_per_prompt=snake_case__)[0]

     assert images.shape[0] == batch_size * num_images_per_prompt



@slow
@require_torch_gpu
class 				A_     (    unittest.TestCase      ):






 '''simple docstring'''




 def 			snake_case__					(						self)			->		Optional[int]:

     """simple docstring"""



     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()


 def 			snake_case__					(						self)			->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase					:   List[Any]      	=					load_image(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png''')
     _UpperCAmelCase					:   List[Any]      	=					load_numpy(
         '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
         '''/shap_e/test_shap_e_img2img_out.npy''')
     _UpperCAmelCase					:   List[str]      	=					ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img''')
     _UpperCAmelCase					:   str      	=					pipe.to(snake_case__)
     pipe.set_progress_bar_config(disable=snake_case__)

     _UpperCAmelCase					:   List[str]      	=					torch.Generator(device=snake_case__).manual_seed(0)

     _UpperCAmelCase					:   Union[str, Any]      	=					pipe(
         snake_case__				,	generator=snake_case__				,	guidance_scale=3.0				,	num_inference_steps=64				,	frame_size=64				,	output_type='''np'''				,	).images[0]

     assert images.shape == (20, 64, 64, 3)

     assert_mean_pixel_difference(snake_case__				,	snake_case__)





def 	lowerCamelCase					(	UpperCamelCase     :				int			,       UpperCamelCase     :				int							)   ->    float:
		return base * power(UpperCamelCase			,       (exponent - 1)							) if exponent else 1


if __name__ == "__main__":
				print('Raise base to the power of exponent using recursion...')
				A						=			int(input('Enter the base: ').strip())
				A						=			int(input('Enter the exponent: ').strip())
				A						=			power(base, abs(exponent))
				if exponent < 0:  # power() does not properly deal w/ negative exponents
								A						=			1 / result
				print(F'''{base} to the power of {exponent} is {result}''')