
"""simple docstring"""



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        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase      ,				unittest.TestCase							):






				'''simple docstring'''



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


				@property
				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Optional[Any]:







											"""simple docstring"""




											return 32


				@property
				def 				__lowerCamelCase	(					self	:			str  )		->  Any:







											"""simple docstring"""




											return 32


				@property
				def 				__lowerCamelCase	(					self	:			Tuple  )		->  Dict:







											"""simple docstring"""




											return self.time_input_dim * 4


				@property
				def 				__lowerCamelCase	(					self	:			str  )		->  int:







											"""simple docstring"""




											return 8


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Optional[int]:







											"""simple docstring"""




											torch.manual_seed(0  )
											_lowerCAmelCase  	=			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				,     )

											_lowerCAmelCase  	=			CLIPVisionModel(UpperCAmelCase_  )
											return model


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







											"""simple docstring"""




											_lowerCAmelCase  	=			CLIPImageProcessor(
											    crop_size=224				,     do_center_crop=UpperCAmelCase_				,     do_normalize=UpperCAmelCase_				,     do_resize=UpperCAmelCase_				,     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 				__lowerCamelCase	(					self	:			List[str]  )		->  Optional[int]:







											"""simple docstring"""




											torch.manual_seed(0  )

											_lowerCAmelCase  	=			{
											    '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,
											}

											_lowerCAmelCase  	=			PriorTransformer(**UpperCAmelCase_  )
											return model


				@property
				def 				__lowerCamelCase	(					self	:			Union[str, Any]  )		->  Tuple:







											"""simple docstring"""




											torch.manual_seed(0  )

											_lowerCAmelCase  	=			{
											    '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,
											    ),
											}
											_lowerCAmelCase  	=			ShapERenderer(**UpperCAmelCase_  )
											return model


				def 				__lowerCamelCase	(					self	:			Any  )		->  List[str]:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.dummy_prior
											_lowerCAmelCase  	=			self.dummy_image_encoder
											_lowerCAmelCase  	=			self.dummy_image_processor
											_lowerCAmelCase  	=			self.dummy_renderer

											_lowerCAmelCase  	=			HeunDiscreteScheduler(
											    beta_schedule='exp'				,     num_train_timesteps=1_024				,     prediction_type='sample'				,     use_karras_sigmas=UpperCAmelCase_				,     clip_sample=UpperCAmelCase_				,     clip_sample_range=1.0				,     )
											_lowerCAmelCase  	=			{
											    'prior': prior,
											    'image_encoder': image_encoder,
											    'image_processor': image_processor,
											    'renderer': renderer,
											    'scheduler': scheduler,
											}

											return components


				def 				__lowerCamelCase	(					self	:			Optional[int]				,     UpperCAmelCase_	:			str				,     UpperCAmelCase_	:			Optional[Any]=0  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			floats_tensor((1, 3, 64, 64)				,     rng=random.Random(UpperCAmelCase_  )  ).to(UpperCAmelCase_  )

											if str(UpperCAmelCase_  ).startswith('mps'  ):
																		_lowerCAmelCase  	=			torch.manual_seed(UpperCAmelCase_  )
											else:
																		_lowerCAmelCase  	=			torch.Generator(device=UpperCAmelCase_  ).manual_seed(UpperCAmelCase_  )
											_lowerCAmelCase  	=			{
											    'image': input_image,
											    'generator': generator,
											    'num_inference_steps': 1,
											    'frame_size': 32,
											    'output_type': 'np',
											}
											return inputs


				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Optional[Any]:







											"""simple docstring"""




											_lowerCAmelCase  	=			'cpu'

											_lowerCAmelCase  	=			self.get_dummy_components()

											_lowerCAmelCase  	=			self.pipeline_class(**UpperCAmelCase_  )
											_lowerCAmelCase  	=			pipe.to(UpperCAmelCase_  )

											pipe.set_progress_bar_config(disable=UpperCAmelCase_  )

											_lowerCAmelCase  	=			pipe(**self.get_dummy_inputs(UpperCAmelCase_  )  )
											_lowerCAmelCase  	=			output.images[0]
											_lowerCAmelCase  	=			image[0, -3:, -3:, -1]

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

											_lowerCAmelCase  	=			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 				__lowerCamelCase	(					self	:			List[Any]  )		->  Optional[int]:







											"""simple docstring"""




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


				def 				__lowerCamelCase	(					self	:			Any  )		->  Any:







											"""simple docstring"""




											_lowerCAmelCase  	=			torch_device == 'cpu'
											_lowerCAmelCase  	=			True
											self._test_inference_batch_single_identical(
											    batch_size=2				,     test_max_difference=UpperCAmelCase_				,     relax_max_difference=UpperCAmelCase_				,     )







				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Dict:







											"""simple docstring"""




											_lowerCAmelCase  	=			self.get_dummy_components()
											_lowerCAmelCase  	=			self.pipeline_class(**UpperCAmelCase_  )
											_lowerCAmelCase  	=			pipe.to(UpperCAmelCase_  )
											pipe.set_progress_bar_config(disable=UpperCAmelCase_  )

											_lowerCAmelCase  	=			1
											_lowerCAmelCase  	=			2

											_lowerCAmelCase  	=			self.get_dummy_inputs(UpperCAmelCase_  )

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

											_lowerCAmelCase  	=			pipe(**UpperCAmelCase_				,     num_images_per_prompt=UpperCAmelCase_  )[0]

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






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






				'''simple docstring'''



				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Optional[Any]:







											"""simple docstring"""




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







				def 				__lowerCamelCase	(					self	:			Any  )		->  Optional[int]:







											"""simple docstring"""




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

											_lowerCAmelCase  	=			torch.Generator(device=UpperCAmelCase_  ).manual_seed(0  )

											_lowerCAmelCase  	=			pipe(
											    UpperCAmelCase_				,     generator=UpperCAmelCase_				,     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(UpperCAmelCase_				,     UpperCAmelCase_  )








"""simple docstring"""



from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


_snake_case          =						logging.get_logger(__name__)

_snake_case          =						{
    '''google/mobilenet_v1_1.0_224''': '''https://huggingface.co/google/mobilenet_v1_1.0_224/resolve/main/config.json''',
    '''google/mobilenet_v1_0.75_192''': '''https://huggingface.co/google/mobilenet_v1_0.75_192/resolve/main/config.json''',
    # See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
}
class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Dict							=					"mobilenet_v1"


				def __init__(					self	:			List[Any]				,     UpperCAmelCase_	:			Optional[int]=3				,     UpperCAmelCase_	:			str=224				,     UpperCAmelCase_	:			Union[str, Any]=1.0				,     UpperCAmelCase_	:			List[str]=8				,     UpperCAmelCase_	:			Union[str, Any]="relu6"				,     UpperCAmelCase_	:			Optional[Any]=True				,     UpperCAmelCase_	:			Optional[int]=0.999				,     UpperCAmelCase_	:			Optional[Any]=0.02				,     UpperCAmelCase_	:			Union[str, Any]=0.001				,     **UpperCAmelCase_	:			List[Any]				,     )		->  Dict:







											"""simple docstring"""




											super().__init__(**UpperCAmelCase_  )

											if depth_multiplier <= 0:
																		raise ValueError('depth_multiplier must be greater than zero.'  )

											_lowerCAmelCase  	=			num_channels
											_lowerCAmelCase  	=			image_size
											_lowerCAmelCase  	=			depth_multiplier
											_lowerCAmelCase  	=			min_depth
											_lowerCAmelCase  	=			hidden_act
											_lowerCAmelCase  	=			tf_padding
											_lowerCAmelCase  	=			classifier_dropout_prob
											_lowerCAmelCase  	=			initializer_range
											_lowerCAmelCase  	=			layer_norm_eps






class        _SCREAMING_SNAKE_CASE  (  UpperCAmelCase							):






				'''simple docstring'''



				SCREAMING_SNAKE_CASE_:							Optional[int]							=					version.parse("1.11"							)


				@property
				def 				__lowerCamelCase	(					self	:			List[str]  )		->  Mapping[str, Mapping[int, str]]:







											"""simple docstring"""




											return OrderedDict([('pixel_values', {0: 'batch'})]  )


				@property
				def 				__lowerCamelCase	(					self	:			Dict  )		->  Mapping[str, Mapping[int, str]]:







											"""simple docstring"""




											if self.task == "image-classification":
																		return OrderedDict([('logits', {0: 'batch'})]  )
											else:
																		return OrderedDict([('last_hidden_state', {0: 'batch'}), ('pooler_output', {0: 'batch'})]  )







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







											"""simple docstring"""




											return 1E-4






