






'''simple docstring'''





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  snake_case__      (					UpperCamelCase     ,				unittest.TestCase):
					a_        =					ShapEPipeline
					a_        =					["prompt"]
					a_        =					["prompt"]
					a_        =					[
					    "num_images_per_prompt",
					    "num_inference_steps",
					    "generator",
					    "latents",
					    "guidance_scale",
					    "frame_size",
					    "output_type",
					    "return_dict",
					]
					a_        =					False




					@property
					def 		A      (  self  :		List[str]      )    ->							int:
								return 32




					@property
					def 		A      (  self  :		str      )    ->							Union[str, Any]:
								return 32




					@property
					def 		A      (  self  :		int      )    ->							Any:
								return self.time_input_dim * 4




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




					@property
					def 		A      (  self  :		Optional[Any]      )    ->							int:
								UpperCAmelCase_      :       List[str]          =       CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''      )
								return tokenizer




					@property
					def 		A      (  self  :		List[str]      )    ->							Optional[Any]:
								torch.manual_seed(0      )
								UpperCAmelCase_      :       Dict          =       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(_A      )




					@property
					def 		A      (  self  :		Union[str, Any]      )    ->							Dict:
								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''',
								    '''encoder_hid_proj_type''': None,
								    '''added_emb_type''': None,
								}

								UpperCAmelCase_      :       Any          =       PriorTransformer(**_A      )
								return model




					@property
					def 		A      (  self  :		List[str]      )    ->							Optional[int]:
								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_      :       str          =       ShapERenderer(**_A      )
								return model




					def 		A      (  self  :		str      )    ->							Optional[int]:
								UpperCAmelCase_      :       str          =       self.dummy_prior
								UpperCAmelCase_      :       List[Any]          =       self.dummy_text_encoder
								UpperCAmelCase_      :       Optional[int]          =       self.dummy_tokenizer
								UpperCAmelCase_      :       str          =       self.dummy_renderer

								UpperCAmelCase_      :       Dict          =       HeunDiscreteScheduler(
								    beta_schedule='''exp'''				, num_train_timesteps=10_24				, prediction_type='''sample'''				, use_karras_sigmas=_A				, clip_sample=_A				, clip_sample_range=1.0				, )
								UpperCAmelCase_      :       Optional[int]          =       {
								    '''prior''': prior,
								    '''text_encoder''': text_encoder,
								    '''tokenizer''': tokenizer,
								    '''renderer''': renderer,
								    '''scheduler''': scheduler,
								}

								return components




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




					def 		A      (  self  :		List[Any]      )    ->							int:
								UpperCAmelCase_      :       Dict          =       '''cpu'''

								UpperCAmelCase_      :       int          =       self.get_dummy_components()

								UpperCAmelCase_      :       int          =       self.pipeline_class(**_A      )
								UpperCAmelCase_      :       Dict          =       pipe.to(_A      )

								pipe.set_progress_bar_config(disable=_A      )

								UpperCAmelCase_      :       Union[str, Any]          =       pipe(**self.get_dummy_inputs(_A      )      )
								UpperCAmelCase_      :       Optional[Any]          =       output.images[0]
								UpperCAmelCase_      :       Union[str, Any]          =       image[0, -3:, -3:, -1]

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

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




					def 		A      (  self  :		Dict      )    ->							str:
								UpperCAmelCase_      :       Optional[Any]          =       torch_device == '''cpu'''
								UpperCAmelCase_      :       Any          =       True

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





					def 		A      (  self  :		Optional[Any]      )    ->							Any:
								UpperCAmelCase_      :       Union[str, Any]          =       self.get_dummy_components()
								UpperCAmelCase_      :       Dict          =       self.pipeline_class(**_A      )
								UpperCAmelCase_      :       str          =       pipe.to(_A      )
								pipe.set_progress_bar_config(disable=_A      )

								UpperCAmelCase_      :       Tuple          =       1
								UpperCAmelCase_      :       Dict          =       2

								UpperCAmelCase_      :       Union[str, Any]          =       self.get_dummy_inputs(_A      )

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

								UpperCAmelCase_      :       Optional[Any]          =       pipe(**_A				, num_images_per_prompt=_A      )[0]

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






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




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





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

								UpperCAmelCase_      :       Tuple          =       torch.Generator(device=_A      ).manual_seed(0      )

								UpperCAmelCase_      :       Tuple          =       pipe(
								    '''a shark'''				, generator=_A				, 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(_A				, _A      )










'''simple docstring'''





import argparse
import os
import re

import packaging.version


_UpperCamelCase						:						Union[str, Any]  =					'examples/'
_UpperCamelCase						:						List[str]  =					{
    'examples': (re.compile(R'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'),
    'init': (re.compile(R'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'),
    'setup': (re.compile(R'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), R'\1version="VERSION",'),
    'doc': (re.compile(R'^(\s*)release\s*=\s*"[^"]+"$', re.MULTILINE), 'release = "VERSION"\n'),
}
_UpperCamelCase						:						Optional[Any]  =					{
    'init': 'src/diffusers/__init__.py',
    'setup': 'setup.py',
}
_UpperCamelCase						:						Any  =					'README.md'
def __UpperCAmelCase   (					A					:			Optional[int]			,       A					:			List[Any]			,       A					:			Tuple		)    ->   Dict:
			with open(A			,       '''r'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						UpperCAmelCase_      :       int          =       f.read()
			UpperCAmelCase_    ,      UpperCAmelCase_      :       Union[str, Any]          =       REPLACE_PATTERNS[pattern]
			UpperCAmelCase_      :       Tuple          =       replace.replace('''VERSION'''			,       A		)
			UpperCAmelCase_      :       Tuple          =       re_pattern.sub(A			,       A		)
			with open(A			,       '''w'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						f.write(A		)
def __UpperCAmelCase   (					A					:			List[str]		)    ->   Any:
			for folder, directories, fnames in os.walk(A		):
						# Removing some of the folders with non-actively maintained examples from the walk
						if "research_projects" in directories:
									directories.remove('''research_projects'''		)
						if "legacy" in directories:
									directories.remove('''legacy'''		)
						for fname in fnames:
									if fname.endswith('''.py'''		):
												update_version_in_file(os.path.join(A			,       A		)			,       A			,       pattern='''examples'''		)
def __UpperCAmelCase   (					A					:			Tuple			,       A					:			Optional[int]=False		)    ->   Tuple:
			for pattern, fname in REPLACE_FILES.items():
						update_version_in_file(A			,       A			,       A		)
			if not patch:
						update_version_in_examples(A		)
def __UpperCAmelCase   (					)    ->   int:
			UpperCAmelCase_      :       List[str]          =       '''🤗 Transformers currently provides the following architectures'''
			UpperCAmelCase_      :       int          =       '''1. Want to contribute a new model?'''
			with open(A			,       '''r'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						UpperCAmelCase_      :       Optional[int]          =       f.readlines()

			# Find the start of the list.
			UpperCAmelCase_      :       List[str]          =       0
			while not lines[start_index].startswith(_start_prompt		):
						start_index += 1
			start_index += 1

			UpperCAmelCase_      :       Any          =       start_index
			# Update the lines in the model list.
			while not lines[index].startswith(_end_prompt		):
						if lines[index].startswith('''1.'''		):
									UpperCAmelCase_      :       Optional[Any]          =       lines[index].replace(
									    '''https://huggingface.co/docs/diffusers/main/model_doc'''			,       '''https://huggingface.co/docs/diffusers/model_doc'''			,       )
						index += 1

			with open(A			,       '''w'''			,       encoding='''utf-8'''			,       newline='''\n'''		) as f:
						f.writelines(A		)
def __UpperCAmelCase   (					)    ->   Dict:
			with open(REPLACE_FILES['''init''']			,       '''r'''		) as f:
						UpperCAmelCase_      :       Any          =       f.read()
			UpperCAmelCase_      :       Union[str, Any]          =       REPLACE_PATTERNS['''init'''][0].search(A		).groups()[0]
			return packaging.version.parse(A		)
def __UpperCAmelCase   (					A					:			str=False		)    ->   List[Any]:
			UpperCAmelCase_      :       Union[str, Any]          =       get_version()
			if patch and default_version.is_devrelease:
						raise ValueError('''Can\'t create a patch version from the dev branch, checkout a released version!'''		)
			if default_version.is_devrelease:
						UpperCAmelCase_      :       Optional[int]          =       default_version.base_version
			elif patch:
						UpperCAmelCase_      :       Any          =       F"{default_version.major}.{default_version.minor}.{default_version.micro + 1}"
			else:
						UpperCAmelCase_      :       Optional[Any]          =       F"{default_version.major}.{default_version.minor + 1}.0"

			# Now let's ask nicely if that's the right one.
			UpperCAmelCase_      :       List[str]          =       input(F"Which version are you releasing? [{default_version}]"		)
			if len(A		) == 0:
						UpperCAmelCase_      :       Tuple          =       default_version

			print(F"Updating version to {version}."		)
			global_version_update(A			,       patch=A		)
def __UpperCAmelCase   (					)    ->   Optional[int]:
			UpperCAmelCase_      :       str          =       get_version()
			UpperCAmelCase_      :       Tuple          =       F"{current_version.major}.{current_version.minor + 1}.0.dev0"
			UpperCAmelCase_      :       Any          =       current_version.base_version

			# Check with the user we got that right.
			UpperCAmelCase_      :       List[Any]          =       input(F"Which version are we developing now? [{dev_version}]"		)
			if len(A		) == 0:
						UpperCAmelCase_      :       Optional[int]          =       dev_version

			print(F"Updating version to {version}."		)
			global_version_update(A		)


#    print("Cleaning main README, don't forget to run `make fix-copies`.")
#    clean_main_ref_in_model_list()


if __name__ == "__main__":
						_UpperCamelCase						:						Tuple  =					argparse.ArgumentParser()
						parser.add_argument('--post_release', action='store_true', help='Whether this is pre or post release.')
						parser.add_argument('--patch', action='store_true', help='Whether or not this is a patch release.')
						_UpperCamelCase						:						Optional[Any]  =					parser.parse_args()
						if not args.post_release:
												pre_release_work(patch=args.patch)
						elif args.patch:
												print('Nothing to do after a patch :-)')
						else:
												post_release_work()


