
'''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 						a   (				__magic_name__				,unittest.TestCase    ):
				_snake_case		    = ShapEImgaImgPipeline
				_snake_case		    = ['''image''']
				_snake_case		    = ['''image''']
				_snake_case		    = [
				    '''num_images_per_prompt''',
				    '''num_inference_steps''',
				    '''generator''',
				    '''latents''',
				    '''guidance_scale''',
				    '''frame_size''',
				    '''output_type''',
				    '''return_dict''',
				]
				_snake_case		    = False




				@property
				def 	__snake_case							(							self	:				str      ):
										return 32




				@property
				def 	__snake_case							(							self	:				Optional[int]      ):
										return 32




				@property
				def 	__snake_case							(							self	:				int      ):
										return self.time_input_dim * 4




				@property
				def 	__snake_case							(							self	:				List[Any]      ):
										return 8




				@property
				def 	__snake_case							(							self	:				Optional[Any]      ):
										torch.manual_seed(0      )
										snake_case       :     List[str] =    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,    )

										snake_case       :     List[Any] =    CLIPVisionModel(SCREAMING_SNAKE_CASE_      )
										return model




				@property
				def 	__snake_case							(							self	:				str      ):
										snake_case       :     Optional[int] =    CLIPImageProcessor(
										    crop_size=2_24,    do_center_crop=SCREAMING_SNAKE_CASE_,    do_normalize=SCREAMING_SNAKE_CASE_,    do_resize=SCREAMING_SNAKE_CASE_,    image_mean=[0.48145466, 0.4578275, 0.40821073],    image_std=[0.26862954, 0.26130258, 0.27577711],    resample=3,    size=2_24,    )

										return image_processor




				@property
				def 	__snake_case							(							self	:				Optional[int]      ):
										torch.manual_seed(0      )

										snake_case       :     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,
										}

										snake_case       :     List[str] =    PriorTransformer(**SCREAMING_SNAKE_CASE_      )
										return model




				@property
				def 	__snake_case							(							self	:				Dict      ):
										torch.manual_seed(0      )

										snake_case       :     List[str] =    {
										    '''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,
										    ),
										}
										snake_case       :     Optional[Any] =    ShapERenderer(**SCREAMING_SNAKE_CASE_      )
										return model




				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     Any =    self.dummy_prior
										snake_case       :     str =    self.dummy_image_encoder
										snake_case       :     Dict =    self.dummy_image_processor
										snake_case       :     Tuple =    self.dummy_renderer

										snake_case       :     Optional[int] =    HeunDiscreteScheduler(
										    beta_schedule='''exp''',    num_train_timesteps=10_24,    prediction_type='''sample''',    use_karras_sigmas=SCREAMING_SNAKE_CASE_,    clip_sample=SCREAMING_SNAKE_CASE_,    clip_sample_range=1.0,    )
										snake_case       :     Dict =    {
										    '''prior''': prior,
										    '''image_encoder''': image_encoder,
										    '''image_processor''': image_processor,
										    '''renderer''': renderer,
										    '''scheduler''': scheduler,
										}

										return components




				def 	__snake_case							(							self	:				Dict,    SCREAMING_SNAKE_CASE_	:				Union[str, Any],    SCREAMING_SNAKE_CASE_	:				Optional[Any]=0      ):
										snake_case       :     int =    floats_tensor((1, 3, 64, 64),    rng=random.Random(SCREAMING_SNAKE_CASE_      )      ).to(SCREAMING_SNAKE_CASE_      )

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




				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     List[str] =    '''cpu'''

										snake_case       :     Optional[Any] =    self.get_dummy_components()

										snake_case       :     List[str] =    self.pipeline_class(**SCREAMING_SNAKE_CASE_      )
										snake_case       :     Optional[Any] =    pipe.to(SCREAMING_SNAKE_CASE_      )

										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_      )

										snake_case       :     Any =    pipe(**self.get_dummy_inputs(SCREAMING_SNAKE_CASE_      )      )
										snake_case       :     Dict =    output.images[0]
										snake_case       :     Optional[int] =    image[0, -3:, -3:, -1]

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

										snake_case       :     Optional[int] =    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]      ):
										# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
										self._test_inference_batch_consistent(batch_sizes=[1, 2]      )




				def 	__snake_case							(							self	:				Optional[int]      ):
										snake_case       :     Union[str, Any] =    torch_device == '''cpu'''
										snake_case       :     int =    True
										self._test_inference_batch_single_identical(
										    batch_size=2,    test_max_difference=SCREAMING_SNAKE_CASE_,    relax_max_difference=SCREAMING_SNAKE_CASE_,    )




				def 	__snake_case							(							self	:				List[Any]      ):
										snake_case       :     Tuple =    self.get_dummy_components()
										snake_case       :     Union[str, Any] =    self.pipeline_class(**SCREAMING_SNAKE_CASE_      )
										snake_case       :     str =    pipe.to(SCREAMING_SNAKE_CASE_      )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_      )

										snake_case       :     List[str] =    1
										snake_case       :     Optional[Any] =    2

										snake_case       :     int =    self.get_dummy_inputs(SCREAMING_SNAKE_CASE_      )

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

										snake_case       :     Dict =    pipe(**SCREAMING_SNAKE_CASE_,    num_images_per_prompt=SCREAMING_SNAKE_CASE_      )[0]

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




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




				def 	__snake_case							(							self	:				Optional[int]      ):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()




				def 	__snake_case							(							self	:				int      ):
										snake_case       :     Dict =    load_image(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/shap_e/corgi.png'''      )
										snake_case       :     Union[str, Any] =    load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
										    '''/shap_e/test_shap_e_img2img_out.npy'''      )
										snake_case       :     Union[str, Any] =    ShapEImgaImgPipeline.from_pretrained('''openai/shap-e-img2img'''      )
										snake_case       :     Any =    pipe.to(SCREAMING_SNAKE_CASE_      )
										pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_      )

										snake_case       :     Any =    torch.Generator(device=SCREAMING_SNAKE_CASE_      ).manual_seed(0      )

										snake_case       :     List[str] =    pipe(
										    SCREAMING_SNAKE_CASE_,    generator=SCREAMING_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(SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_      )



'''simple docstring'''





from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCAmelCase    					=   {
    "configuration_convbert": ["CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "ConvBertConfig", "ConvBertOnnxConfig"],
    "tokenization_convbert": ["ConvBertTokenizer"],
}

try:
						if not is_tokenizers_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCAmelCase    					=   ["ConvBertTokenizerFast"]

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCAmelCase    					=   [
						    "CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
						    "ConvBertForMaskedLM",
						    "ConvBertForMultipleChoice",
						    "ConvBertForQuestionAnswering",
						    "ConvBertForSequenceClassification",
						    "ConvBertForTokenClassification",
						    "ConvBertLayer",
						    "ConvBertModel",
						    "ConvBertPreTrainedModel",
						    "load_tf_weights_in_convbert",
						]


try:
						if not is_tf_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCAmelCase    					=   [
						    "TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST",
						    "TFConvBertForMaskedLM",
						    "TFConvBertForMultipleChoice",
						    "TFConvBertForQuestionAnswering",
						    "TFConvBertForSequenceClassification",
						    "TFConvBertForTokenClassification",
						    "TFConvBertLayer",
						    "TFConvBertModel",
						    "TFConvBertPreTrainedModel",
						]


if TYPE_CHECKING:
						from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig
						from .tokenization_convbert import ConvBertTokenizer

						try:
												if not is_tokenizers_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .tokenization_convbert_fast import ConvBertTokenizerFast

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_convbert import (
												    CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    ConvBertForMaskedLM,
												    ConvBertForMultipleChoice,
												    ConvBertForQuestionAnswering,
												    ConvBertForSequenceClassification,
												    ConvBertForTokenClassification,
												    ConvBertLayer,
												    ConvBertModel,
												    ConvBertPreTrainedModel,
												    load_tf_weights_in_convbert,
												)

						try:
												if not is_tf_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_tf_convbert import (
												    TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
												    TFConvBertForMaskedLM,
												    TFConvBertForMultipleChoice,
												    TFConvBertForQuestionAnswering,
												    TFConvBertForSequenceClassification,
												    TFConvBertForTokenClassification,
												    TFConvBertLayer,
												    TFConvBertModel,
												    TFConvBertPreTrainedModel,
												)


else:
						import sys

						UpperCAmelCase    					=   _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)

