


"""simple docstring"""





import copy
import random

from transformers import CLIPTokenizer
class 		SCREAMING_SNAKE_CASE_							(    _A   ):
				"""simple docstring"""




				def __init__(     self  :List[str]						,    *__lowercase  :List[str]						,    **__lowercase  :Optional[int]			):
											super().__init__(*UpperCamelCase__						,    **UpperCamelCase__			)
											__lowerCamelCase      :      List[Any]         ={}




				def 					__lowercase  (     self  :Optional[Any]						,    __lowercase  :Optional[Any]						,    *__lowercase  :Union[str, Any]						,    **__lowercase  :Optional[int]			):
											__lowerCamelCase      :      Tuple         =super().add_tokens(UpperCamelCase__						,    *UpperCamelCase__						,    **UpperCamelCase__			)
											if num_added_tokens == 0:
																		raise ValueError(
																		    f'The tokenizer already contains the token {placeholder_token}. Please pass a different'
																		    ''' `placeholder_token` that is not already in the tokenizer.'''			)




				def 					__lowercase  (     self  :Any						,    __lowercase  :Union[str, Any]						,    *__lowercase  :Optional[Any]						,    __lowercase  :str=1						,    **__lowercase  :Dict			):
											__lowerCamelCase      :      Dict         =[]
											if num_vec_per_token == 1:
																		self.try_adding_tokens(UpperCamelCase__						,    *UpperCamelCase__						,    **UpperCamelCase__			)
																		output.append(UpperCamelCase__			)
											else:
																		__lowerCamelCase      :      Any         =[]
																		for i in range(UpperCamelCase__			):
																									__lowerCamelCase      :      Optional[int]         =placeholder_token + f'_{i}'
																									self.try_adding_tokens(UpperCamelCase__						,    *UpperCamelCase__						,    **UpperCamelCase__			)
																									output.append(UpperCamelCase__			)
																									# handle cases where there is a new placeholder token that contains the current placeholder token but is larger
											for token in self.token_map:
																		if token in placeholder_token:
																									raise ValueError(
																									    f'The tokenizer already has placeholder token {token} that can get confused with'
																									    f' {placeholder_token}keep placeholder tokens independent'			)
											__lowerCamelCase      :      List[str]         =output




				def 					__lowercase  (     self  :Any						,    __lowercase  :Union[str, Any]						,    __lowercase  :List[str]=False						,    __lowercase  :List[Any]=1.0			):






											if isinstance(UpperCamelCase__						,    UpperCamelCase__			):
																		__lowerCamelCase      :      str         =[]
																		for i in range(len(UpperCamelCase__			)			):
																									output.append(self.replace_placeholder_tokens_in_text(text[i]						,    vector_shuffle=UpperCamelCase__			)			)
																		return output
											for placeholder_token in self.token_map:
																		if placeholder_token in text:
																									__lowerCamelCase      :      Union[str, Any]         =self.token_map[placeholder_token]
																									__lowerCamelCase      :      Dict         =tokens[: 1 + int(len(UpperCamelCase__			) * prop_tokens_to_load			)]
																									if vector_shuffle:
																																__lowerCamelCase      :      int         =copy.copy(UpperCamelCase__			)
																																random.shuffle(UpperCamelCase__			)
																									__lowerCamelCase      :      int         =text.replace(UpperCamelCase__						,    ''' '''.join(UpperCamelCase__			)			)
											return text




				def __call__(     self  :Optional[int]						,    __lowercase  :List[str]						,    *__lowercase  :Dict						,    __lowercase  :List[Any]=False						,    __lowercase  :str=1.0						,    **__lowercase  :str			):
											return super().__call__(
											    self.replace_placeholder_tokens_in_text(
											        UpperCamelCase__						,    vector_shuffle=UpperCamelCase__						,    prop_tokens_to_load=UpperCamelCase__			)						,    *UpperCamelCase__						,    **UpperCamelCase__						,    )




				def 					__lowercase  (     self  :int						,    __lowercase  :List[str]						,    *__lowercase  :List[str]						,    __lowercase  :Optional[int]=False						,    __lowercase  :Union[str, Any]=1.0						,    **__lowercase  :Optional[Any]			):
											return super().encode(
											    self.replace_placeholder_tokens_in_text(
											        UpperCamelCase__						,    vector_shuffle=UpperCamelCase__						,    prop_tokens_to_load=UpperCamelCase__			)						,    *UpperCamelCase__						,    **UpperCamelCase__						,    )











"""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 		SCREAMING_SNAKE_CASE_							(    snake_case__       ,  unittest.TestCase   ):
				"""simple docstring"""
				__snake_case   :       Union[str, Any]	 =		LDMTextToImagePipeline
				__snake_case   :       Optional[Any]	 =		TEXT_TO_IMAGE_PARAMS - {
				    """negative_prompt""",
				    """negative_prompt_embeds""",
				    """cross_attention_kwargs""",
				    """prompt_embeds""",
				}
				__snake_case   :       str	 =		PipelineTesterMixin.required_optional_params - {
				    """num_images_per_prompt""",
				    """callback""",
				    """callback_steps""",
				}
				__snake_case   :       Union[str, Any]	 =		TEXT_TO_IMAGE_BATCH_PARAMS
				__snake_case   :       Optional[Any]	 =		False




				def 					__lowercase  (     self  :List[str]			):
											torch.manual_seed(0			)
											__lowerCamelCase      :      str         =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						,    )
											__lowerCamelCase      :      str         =DDIMScheduler(
											    beta_start=0.00085						,    beta_end=0.012						,    beta_schedule='''scaled_linear'''						,    clip_sample=__lowercase						,    set_alpha_to_one=__lowercase						,    )
											torch.manual_seed(0			)
											__lowerCamelCase      :      Optional[int]         =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			)
											__lowerCamelCase      :      Any         =CLIPTextConfig(
											    bos_token_id=0						,    eos_token_id=2						,    hidden_size=32						,    intermediate_size=37						,    layer_norm_eps=1e-0_5						,    num_attention_heads=4						,    num_hidden_layers=5						,    pad_token_id=1						,    vocab_size=1000						,    )
											__lowerCamelCase      :      Optional[int]         =CLIPTextModel(__lowercase			)
											__lowerCamelCase      :      Dict         =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''			)

											__lowerCamelCase      :      Optional[int]         ={
											    '''unet''': unet,
											    '''scheduler''': scheduler,
											    '''vqvae''': vae,
											    '''bert''': text_encoder,
											    '''tokenizer''': tokenizer,
											}
											return components




				def 					__lowercase  (     self  :int						,    __lowercase  :Optional[int]						,    __lowercase  :Optional[Any]=0			):
											if str(__lowercase			).startswith('''mps'''			):
																		__lowerCamelCase      :      Any         =torch.manual_seed(__lowercase			)
											else:
																		__lowerCamelCase      :      str         =torch.Generator(device=__lowercase			).manual_seed(__lowercase			)
											__lowerCamelCase      :      Any         ={
											    '''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 					__lowercase  (     self  :List[str]			):
											__lowerCamelCase      :      List[str]         ='''cpu'''  # ensure determinism for the device-dependent torch.Generator

											__lowerCamelCase      :      str         =self.get_dummy_components()
											__lowerCamelCase      :      Optional[int]         =LDMTextToImagePipeline(**__lowercase			)
											pipe.to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

											__lowerCamelCase      :      str         =self.get_dummy_inputs(__lowercase			)
											__lowerCamelCase      :      List[Any]         =pipe(**__lowercase			).images
											__lowerCamelCase      :      Optional[int]         =image[0, -3:, -3:, -1]

											assert image.shape == (1, 16, 16, 3)
											__lowerCamelCase      :      Optional[Any]         =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 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Any			):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




				def 					__lowercase  (     self  :int						,    __lowercase  :Any						,    __lowercase  :Optional[int]=torch.floataa						,    __lowercase  :Dict=0			):
											__lowerCamelCase      :      List[str]         =torch.manual_seed(__lowercase			)
											__lowerCamelCase      :      List[str]         =np.random.RandomState(__lowercase			).standard_normal((1, 4, 32, 32)			)
											__lowerCamelCase      :      List[str]         =torch.from_numpy(__lowercase			).to(device=__lowercase						,    dtype=__lowercase			)
											__lowerCamelCase      :      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 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      int         =LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

											__lowerCamelCase      :      Tuple         =self.get_inputs(__lowercase			)
											__lowerCamelCase      :      Optional[Any]         =pipe(**__lowercase			).images
											__lowerCamelCase      :      Union[str, Any]         =image[0, -3:, -3:, -1].flatten()

											assert image.shape == (1, 256, 256, 3)
											__lowerCamelCase      :      Union[str, Any]         =np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]			)
											__lowerCamelCase      :      Dict         =np.abs(expected_slice - image_slice			).max()
											assert max_diff < 1e-3

@nightly
@require_torch_gpu
class 		SCREAMING_SNAKE_CASE_							(    unittest.TestCase   ):
				"""simple docstring"""




				def 					__lowercase  (     self  :Any			):
											super().tearDown()
											gc.collect()
											torch.cuda.empty_cache()




				def 					__lowercase  (     self  :Dict						,    __lowercase  :Optional[Any]						,    __lowercase  :int=torch.floataa						,    __lowercase  :Dict=0			):
											__lowerCamelCase      :      Any         =torch.manual_seed(__lowercase			)
											__lowerCamelCase      :      Dict         =np.random.RandomState(__lowercase			).standard_normal((1, 4, 32, 32)			)
											__lowerCamelCase      :      str         =torch.from_numpy(__lowercase			).to(device=__lowercase						,    dtype=__lowercase			)
											__lowerCamelCase      :      Dict         ={
											    '''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 					__lowercase  (     self  :Tuple			):
											__lowerCamelCase      :      Optional[int]         =LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(__lowercase			)
											pipe.set_progress_bar_config(disable=__lowercase			)

											__lowerCamelCase      :      List[Any]         =self.get_inputs(__lowercase			)
											__lowerCamelCase      :      Optional[int]         =pipe(**__lowercase			).images[0]

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




