



"""simple docstring"""







import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class        __A       (	A_     ,unittest.TestCase    ):







		'''simple docstring'''





		lowerCAmelCase			:					Any   	=				LDMTextToImagePipeline
		lowerCAmelCase			:					str   	=				TEXT_TO_IMAGE_PARAMS - {
		    "negative_prompt",
		    "negative_prompt_embeds",
		    "cross_attention_kwargs",
		    "prompt_embeds",
		}
		lowerCAmelCase			:					List[Any]   	=				PipelineTesterMixin.required_optional_params - {
		    "num_images_per_prompt",
		    "callback",
		    "callback_steps",
		}
		lowerCAmelCase			:					List[Any]   	=				TEXT_TO_IMAGE_BATCH_PARAMS
		lowerCAmelCase			:					Optional[int]   	=				False







		def 					UpperCAmelCase    (	self						:  Any						)					->		int:






				"""simple docstring"""



				torch.manual_seed(0						)
				lowercase__   :    Any				=			UNetaDConditionModel(
				    block_out_channels=(32, 64)			,layers_per_block=2			,sample_size=32			,in_channels=4			,out_channels=4			,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')			,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')			,cross_attention_dim=32			,)
				lowercase__   :    Optional[int]				=			DDIMScheduler(
				    beta_start=0.0_0085			,beta_end=0.012			,beta_schedule='''scaled_linear'''			,clip_sample=_snake_case			,set_alpha_to_one=_snake_case			,)
				torch.manual_seed(0						)
				lowercase__   :    str				=			AutoencoderKL(
				    block_out_channels=(32, 64)			,in_channels=3			,out_channels=3			,down_block_types=('''DownEncoderBlock2D''', '''DownEncoderBlock2D''')			,up_block_types=('''UpDecoderBlock2D''', '''UpDecoderBlock2D''')			,latent_channels=4			,)
				torch.manual_seed(0						)
				lowercase__   :    int				=			CLIPTextConfig(
				    bos_token_id=0			,eos_token_id=2			,hidden_size=32			,intermediate_size=37			,layer_norm_eps=1e-05			,num_attention_heads=4			,num_hidden_layers=5			,pad_token_id=1			,vocab_size=1_000			,)
				lowercase__   :    int				=			CLIPTextModel(_snake_case						)
				lowercase__   :    Tuple				=			CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''						)

				lowercase__   :    Dict				=			{
				    '''unet''': unet,
				    '''scheduler''': scheduler,
				    '''vqvae''': vae,
				    '''bert''': text_encoder,
				    '''tokenizer''': tokenizer,
				}
				return components







		def 					UpperCAmelCase    (	self						:  Union[str, Any]			,_snake_case						:  Tuple			,_snake_case						:  Union[str, Any]=0						)					->		List[str]:






				"""simple docstring"""



				if str(_snake_case						).startswith('''mps'''						):
						lowercase__   :    List[str]				=			torch.manual_seed(_snake_case						)
				else:
						lowercase__   :    Optional[int]				=			torch.Generator(device=_snake_case						).manual_seed(_snake_case						)
				lowercase__   :    Dict				=			{
				    '''prompt''': '''A painting of a squirrel eating a burger''',
				    '''generator''': generator,
				    '''num_inference_steps''': 2,
				    '''guidance_scale''': 6.0,
				    '''output_type''': '''numpy''',
				}
				return inputs







		def 					UpperCAmelCase    (	self						:  Any						)					->		int:






				"""simple docstring"""



				lowercase__   :    Optional[Any]				=			'''cpu'''  # ensure determinism for the device-dependent torch.Generator

				lowercase__   :    Optional[int]				=			self.get_dummy_components()
				lowercase__   :    Tuple				=			LDMTextToImagePipeline(**_snake_case						)
				pipe.to(_snake_case						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    Union[str, Any]				=			self.get_dummy_inputs(_snake_case						)
				lowercase__   :    List[str]				=			pipe(**_snake_case						).images
				lowercase__   :    str				=			image[0, -3:, -3:, -1]

				assert image.shape == (1, 16, 16, 3)
				lowercase__   :    Optional[int]				=			np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]						)

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





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







		'''simple docstring'''





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






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  Dict			,_snake_case						:  int			,_snake_case						:  List[Any]=torch.floataa			,_snake_case						:  int=0						)					->		Any:






				"""simple docstring"""



				lowercase__   :    Union[str, Any]				=			torch.manual_seed(_snake_case						)
				lowercase__   :    List[str]				=			np.random.RandomState(_snake_case						).standard_normal((1, 4, 32, 32)						)
				lowercase__   :    Any				=			torch.from_numpy(_snake_case						).to(device=_snake_case			,dtype=_snake_case						)
				lowercase__   :    Any				=			{
				    '''prompt''': '''A painting of a squirrel eating a burger''',
				    '''latents''': latents,
				    '''generator''': generator,
				    '''num_inference_steps''': 3,
				    '''guidance_scale''': 6.0,
				    '''output_type''': '''numpy''',
				}
				return inputs







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''						).to(_snake_case						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    Dict				=			self.get_inputs(_snake_case						)
				lowercase__   :    int				=			pipe(**_snake_case						).images
				lowercase__   :    Optional[Any]				=			image[0, -3:, -3:, -1].flatten()

				assert image.shape == (1, 256, 256, 3)
				lowercase__   :    List[Any]				=			np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]						)
				lowercase__   :    Optional[Any]				=			np.abs(expected_slice - image_slice						).max()
				assert max_diff < 1e-3





@nightly
@require_torch_gpu
class        __A       (	unittest.TestCase    ):







		'''simple docstring'''





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






				"""simple docstring"""



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







		def 					UpperCAmelCase    (	self						:  str			,_snake_case						:  Union[str, Any]			,_snake_case						:  int=torch.floataa			,_snake_case						:  Any=0						)					->		Dict:






				"""simple docstring"""



				lowercase__   :    List[Any]				=			torch.manual_seed(_snake_case						)
				lowercase__   :    List[Any]				=			np.random.RandomState(_snake_case						).standard_normal((1, 4, 32, 32)						)
				lowercase__   :    Dict				=			torch.from_numpy(_snake_case						).to(device=_snake_case			,dtype=_snake_case						)
				lowercase__   :    int				=			{
				    '''prompt''': '''A painting of a squirrel eating a burger''',
				    '''latents''': latents,
				    '''generator''': generator,
				    '''num_inference_steps''': 50,
				    '''guidance_scale''': 6.0,
				    '''output_type''': '''numpy''',
				}
				return inputs







		def 					UpperCAmelCase    (	self						:  Tuple						)					->		List[str]:






				"""simple docstring"""



				lowercase__   :    str				=			LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''						).to(_snake_case						)
				pipe.set_progress_bar_config(disable=_snake_case						)

				lowercase__   :    int				=			self.get_inputs(_snake_case						)
				lowercase__   :    str				=			pipe(**_snake_case						).images[0]

				lowercase__   :    List[Any]				=			load_numpy(
				    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''						)
				lowercase__   :    List[Any]				=			np.abs(expected_image - image						).max()
				assert max_diff < 1e-3






"""simple docstring"""






lowercase__     						=						{
    """meter""": """m""",
    """kilometer""": """km""",
    """megametre""": """Mm""",
    """gigametre""": """Gm""",
    """terametre""": """Tm""",
    """petametre""": """Pm""",
    """exametre""": """Em""",
    """zettametre""": """Zm""",
    """yottametre""": """Ym""",
}
# Exponent of the factor(meter)
lowercase__     						=						{
    """m""": 0,
    """km""": 3,
    """Mm""": 6,
    """Gm""": 9,
    """Tm""": 12,
    """Pm""": 15,
    """Em""": 18,
    """Zm""": 21,
    """Ym""": 24,
}







def      _snake_case			(				lowercase__							,    lowercase__							,    lowercase__		):
				_lowerCamelCase     :			List[Any]    =    from_type.lower().strip('s'		)
				_lowerCamelCase     :			List[Any]    =    to_type.lower().strip('s'		)

				_lowerCamelCase     :			Optional[int]    =    UNIT_SYMBOL.get(lowercase__							,    lowercase__		)
				_lowerCamelCase     :			Any    =    UNIT_SYMBOL.get(lowercase__							,    lowercase__		)

				if from_sanitized not in METRIC_CONVERSION:
								_lowerCamelCase     :			Tuple    =    (
								    f'''Invalid \'from_type\' value: {from_type!r}.\n'''
								    f'''Conversion abbreviations are: {', '.join(lowercase__		)}'''
								)
								raise ValueError(lowercase__		)
				if to_sanitized not in METRIC_CONVERSION:
								_lowerCamelCase     :			Any    =    (
								    f'''Invalid \'to_type\' value: {to_type!r}.\n'''
								    f'''Conversion abbreviations are: {', '.join(lowercase__		)}'''
								)
								raise ValueError(lowercase__		)
				_lowerCamelCase     :			List[Any]    =    METRIC_CONVERSION[from_sanitized]
				_lowerCamelCase     :			int    =    METRIC_CONVERSION[to_sanitized]
				_lowerCamelCase     :			List[str]    =    1

				if from_exponent > to_exponent:
								_lowerCamelCase     :			List[str]    =    from_exponent - to_exponent
				else:
								_lowerCamelCase     :			List[Any]    =    -(to_exponent - from_exponent)

				return value * pow(10							,    lowercase__		)


if __name__ == "__main__":
			from doctest import testmod

			testmod()