






import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import HeunDiscreteScheduler, PriorTransformer, ShapEPipeline
from diffusers.pipelines.shap_e import ShapERenderer
from diffusers.utils import 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(	a_    ,  unittest.TestCase	):
							_UpperCAmelCase     =       ShapEPipeline
							_UpperCAmelCase     =       ["prompt"]
							_UpperCAmelCase     =       ["prompt"]
							_UpperCAmelCase     =       [
							    "num_images_per_prompt",
							    "num_inference_steps",
							    "generator",
							    "latents",
							    "guidance_scale",
							    "frame_size",
							    "output_type",
							    "return_dict",
							]
							_UpperCAmelCase     =       False
							@property
							def lowerCAmelCase_ (     self:      List[Any]						)		->		Dict:
											return 32
							@property
							def lowerCAmelCase_ (     self:      Tuple						)		->		Optional[Any]:
											return 32
							@property
							def lowerCAmelCase_ (     self:      int						)		->		Optional[int]:
											return self.time_input_dim * 4
							@property
							def lowerCAmelCase_ (     self:      List[str]						)		->		Union[str, Any]:
											return 8
							@property
							def lowerCAmelCase_ (     self:      str						)		->		Optional[int]:
											snake_case__									=     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'						)
											return tokenizer
							@property
							def lowerCAmelCase_ (     self:      List[Any]						)		->		Optional[Any]:
											torch.manual_seed(0						)
											snake_case__									=     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=37       ,	layer_norm_eps=1e-05       ,	num_attention_heads=4       ,	num_hidden_layers=5       ,	pad_token_id=1       ,	vocab_size=10_00       ,	)
											return CLIPTextModelWithProjection(UpperCamelCase						)
							@property
							def lowerCAmelCase_ (     self:      List[Any]						)		->		Optional[int]:
											torch.manual_seed(0						)

											snake_case__									=     {
											    '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',
											    'encoder_hid_proj_type': None,
											    'added_emb_type': None,
											}

											snake_case__									=     PriorTransformer(**UpperCamelCase						)
											return model
							@property
							def lowerCAmelCase_ (     self:      str						)		->		Union[str, Any]:
											torch.manual_seed(0						)

											snake_case__									=     {
											    '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__									=     ShapERenderer(**UpperCamelCase						)
											return model
							def lowerCAmelCase_ (     self:      Tuple						)		->		List[str]:
											snake_case__									=     self.dummy_prior
											snake_case__									=     self.dummy_text_encoder
											snake_case__									=     self.dummy_tokenizer
											snake_case__									=     self.dummy_renderer

											snake_case__									=     HeunDiscreteScheduler(
											    beta_schedule='exp'       ,	num_train_timesteps=10_24       ,	prediction_type='sample'       ,	use_karras_sigmas=UpperCamelCase       ,	clip_sample=UpperCamelCase       ,	clip_sample_range=1.0       ,	)
											snake_case__									=     {
											    'prior': prior,
											    'text_encoder': text_encoder,
											    'tokenizer': tokenizer,
											    'renderer': renderer,
											    'scheduler': scheduler,
											}

											return components
							def lowerCAmelCase_ (     self:      Optional[int]       ,	UpperCamelCase:      int       ,	UpperCamelCase:      Tuple=0						)		->		Any:
											if str(UpperCamelCase						).startswith('mps'						):
															snake_case__									=     torch.manual_seed(UpperCamelCase						)
											else:
															snake_case__									=     torch.Generator(device=UpperCamelCase						).manual_seed(UpperCamelCase						)
											snake_case__									=     {
											    'prompt': 'horse',
											    'generator': generator,
											    'num_inference_steps': 1,
											    'frame_size': 32,
											    'output_type': 'np',
											}
											return inputs
							def lowerCAmelCase_ (     self:      Dict						)		->		Optional[Any]:
											snake_case__									=     'cpu'

											snake_case__									=     self.get_dummy_components()

											snake_case__									=     self.pipeline_class(**UpperCamelCase						)
											snake_case__									=     pipe.to(UpperCamelCase						)

											pipe.set_progress_bar_config(disable=UpperCamelCase						)

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

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

											snake_case__									=     np.array(
											    [
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											        0.00_039_216,
											    ]						)

											assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2
							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		Optional[int]:
											# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
											self._test_inference_batch_consistent(batch_sizes=[1, 2]						)
							def lowerCAmelCase_ (     self:      List[str]						)		->		Optional[int]:
											snake_case__									=     torch_device == 'cpu'
											snake_case__									=     True

											self._test_inference_batch_single_identical(
											    batch_size=2       ,	test_max_difference=UpperCamelCase       ,	relax_max_difference=UpperCamelCase       ,	)


							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		Optional[int]:
											snake_case__									=     self.get_dummy_components()
											snake_case__									=     self.pipeline_class(**UpperCamelCase						)
											snake_case__									=     pipe.to(UpperCamelCase						)
											pipe.set_progress_bar_config(disable=UpperCamelCase						)

											snake_case__									=     1
											snake_case__									=     2

											snake_case__									=     self.get_dummy_inputs(UpperCamelCase						)

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

											snake_case__									=     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	):
							def lowerCAmelCase_ (     self:      Union[str, Any]						)		->		int:
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()


							def lowerCAmelCase_ (     self:      int						)		->		Union[str, Any]:
											snake_case__									=     load_numpy(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
											    '/shap_e/test_shap_e_np_out.npy'						)
											snake_case__									=     ShapEPipeline.from_pretrained('openai/shap-e'						)
											snake_case__									=     pipe.to(UpperCamelCase						)
											pipe.set_progress_bar_config(disable=UpperCamelCase						)

											snake_case__									=     torch.Generator(device=UpperCamelCase						).manual_seed(0						)

											snake_case__									=     pipe(
											    'a shark'       ,	generator=UpperCamelCase       ,	guidance_scale=15.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						)












import doctest
import logging
import os
import unittest
from pathlib import Path
from typing import List, Union

import transformers
from transformers.testing_utils import require_tf, require_torch, slow


__UpperCamelCase					:		Optional[Any]	  =						logging.getLogger()


@unittest.skip("Temporarily disable the doc tests."	)
@require_torch
@require_tf
@slow
class   __SCREAMING_SNAKE_CASE(	unittest.TestCase	):
							def lowerCAmelCase_ (     self:      Dict       ,	UpperCamelCase:      Path       ,	UpperCamelCase:      Union[str, None] = None       ,	UpperCamelCase:      Union[List[str], None] = None       ,	UpperCamelCase:      Union[str, List[str], None] = None       ,	UpperCamelCase:      bool = True       ,	)		->		int:
											snake_case__									=     [file for file in os.listdir(UpperCamelCase						) if os.path.isfile(os.path.join(UpperCamelCase       ,	UpperCamelCase						)						)]

											if identifier is not None:
															snake_case__									=     [file for file in files if identifier in file]

											if n_identifier is not None:
															if isinstance(UpperCamelCase       ,	UpperCamelCase						):
																			for n_ in n_identifier:
																							snake_case__									=     [file for file in files if n_ not in file]
															else:
																			snake_case__									=     [file for file in files if n_identifier not in file]

											snake_case__									=     ignore_files or []
											ignore_files.append('__init__.py'						)
											snake_case__									=     [file for file in files if file not in ignore_files]

											for file in files:
															# Open all files
															print('Testing'       ,	UpperCamelCase						)

															if only_modules:
																			snake_case__									=     file.split('.'						)[0]
																			try:
																							snake_case__									=     getattr(UpperCamelCase       ,	UpperCamelCase						)
																							snake_case__									=     doctest.DocTestSuite(UpperCamelCase						)
																							snake_case__									=     unittest.TextTestRunner().run(UpperCamelCase						)
																							self.assertIs(len(result.failures						)       ,	0						)
																			except AttributeError:
																							logger.info(F'''{module_identifier} is not a module.'''						)
															else:
																			snake_case__									=     doctest.testfile(str('..' / directory / file						)       ,	optionflags=doctest.ELLIPSIS						)
																			self.assertIs(result.failed       ,	0						)
							def lowerCAmelCase_ (     self:      Tuple						)		->		int:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'modeling'
											snake_case__									=     [
											    'modeling_ctrl.py',
											    'modeling_tf_ctrl.py',
											]
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase       ,	ignore_files=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Optional[int]						)		->		str:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'tokenization'
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Optional[Any]						)		->		int:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     'configuration'
											self.analyze_directory(UpperCamelCase       ,	identifier=UpperCamelCase						)
							def lowerCAmelCase_ (     self:      Dict						)		->		List[Any]:
											snake_case__									=     Path('src/transformers'						)
											snake_case__									=     ['configuration', 'modeling', 'tokenization']
											self.analyze_directory(UpperCamelCase       ,	n_identifier=UpperCamelCase						)


							def lowerCAmelCase_ (     self:      Tuple						)		->		Union[str, Any]:
											snake_case__									=     Path('docs/source'						)
											snake_case__									=     ['favicon.ico']
											self.analyze_directory(UpperCamelCase       ,	ignore_files=UpperCamelCase       ,	only_modules=UpperCamelCase						)




