
"""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 	lowerCAmelCase_						(a__ ,					unittest.TestCase  ):


				"""simple docstring"""



				__UpperCamelCase      :						str					       =   LDMTextToImagePipeline
				__UpperCamelCase      :						Dict					       =   TEXT_TO_IMAGE_PARAMS - {
				    '''negative_prompt''',
				    '''negative_prompt_embeds''',
				    '''cross_attention_kwargs''',
				    '''prompt_embeds''',
				}
				__UpperCamelCase      :						List[str]					       =   PipelineTesterMixin.required_optional_params - {
				    '''num_images_per_prompt''',
				    '''callback''',
				    '''callback_steps''',
				}
				__UpperCamelCase      :						Any					       =   TEXT_TO_IMAGE_BATCH_PARAMS
				__UpperCamelCase      :						Union[str, Any]					       =   False



				def 	__magic_name__    (self    )					->		List[str]:



											"""simple docstring"""




											torch.manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       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   ,       )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   DDIMScheduler(
											    beta_start=0.00085   ,       beta_end=0.012   ,       beta_schedule="""scaled_linear"""   ,       clip_sample=SCREAMING_SNAKE_CASE__   ,       set_alpha_to_one=SCREAMING_SNAKE_CASE__   ,       )
											torch.manual_seed(0    )
											SCREAMING_SNAKE_CASE__						:       List[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    )
											SCREAMING_SNAKE_CASE__						:       List[str]           =   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=10_00   ,       )
											SCREAMING_SNAKE_CASE__						:       Dict           =   CLIPTextModel(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Any           =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    )

											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   {
											    """unet""": unet,
											    """scheduler""": scheduler,
											    """vqvae""": vae,
											    """bert""": text_encoder,
											    """tokenizer""": tokenizer,
											}
											return components



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=0    )					->		Optional[int]:



											"""simple docstring"""




											if str(SCREAMING_SNAKE_CASE__    ).startswith("""mps"""    ):
																		SCREAMING_SNAKE_CASE__						:       Optional[int]           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											else:
																		SCREAMING_SNAKE_CASE__						:       int           =   torch.Generator(device=SCREAMING_SNAKE_CASE__    ).manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   {
											    """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 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[Any]           =   """cpu"""  # ensure determinism for the device-dependent torch.Generator

											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   self.get_dummy_components()
											SCREAMING_SNAKE_CASE__						:       str           =   LDMTextToImagePipeline(**SCREAMING_SNAKE_CASE__    )
											pipe.to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

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

											assert image.shape == (1, 16, 16, 3)
											SCREAMING_SNAKE_CASE__						:       List[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 	lowerCAmelCase_						(unittest.TestCase  ):


				"""simple docstring"""



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




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



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=torch.floataa   ,       SCREAMING_SNAKE_CASE__=0    )					->		List[str]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       List[str]           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[int]           =   np.random.RandomState(SCREAMING_SNAKE_CASE__    ).standard_normal((1, 4, 32, 32)    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   torch.from_numpy(SCREAMING_SNAKE_CASE__    ).to(device=SCREAMING_SNAKE_CASE__   ,       dtype=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Tuple           =   {
											    """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 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""    ).to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

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

											assert image.shape == (1, 2_56, 2_56, 3)
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   np.array([0.51825, 0.52850, 0.52543, 0.54258, 0.52304, 0.52569, 0.54363, 0.55276, 0.56878]    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   np.abs(expected_slice - image_slice    ).max()
											assert max_diff < 1E-3






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


				"""simple docstring"""



				def 	__magic_name__    (self    )					->		str:



											"""simple docstring"""




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



				def 	__magic_name__    (self   ,       SCREAMING_SNAKE_CASE__   ,       SCREAMING_SNAKE_CASE__=torch.floataa   ,       SCREAMING_SNAKE_CASE__=0    )					->		Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Dict           =   torch.manual_seed(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Any           =   np.random.RandomState(SCREAMING_SNAKE_CASE__    ).standard_normal((1, 4, 32, 32)    )
											SCREAMING_SNAKE_CASE__						:       str           =   torch.from_numpy(SCREAMING_SNAKE_CASE__    ).to(device=SCREAMING_SNAKE_CASE__   ,       dtype=SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Optional[Any]           =   {
											    """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 	__magic_name__    (self    )					->		Tuple:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__						:       Any           =   LDMTextToImagePipeline.from_pretrained("""CompVis/ldm-text2im-large-256"""    ).to(SCREAMING_SNAKE_CASE__    )
											pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__    )

											SCREAMING_SNAKE_CASE__						:       Any           =   self.get_inputs(SCREAMING_SNAKE_CASE__    )
											SCREAMING_SNAKE_CASE__						:       Union[str, Any]           =   pipe(**SCREAMING_SNAKE_CASE__    ).images[0]

											SCREAMING_SNAKE_CASE__						:       str           =   load_numpy(
											    """https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy"""    )
											SCREAMING_SNAKE_CASE__						:       Dict           =   np.abs(expected_image - image    ).max()
											assert max_diff < 1E-3





def       A	(    _lowercase		,  _lowercase						):
						SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							len(_lowercase						)
						SCREAMING_SNAKE_CASE							:    Any							=							len(_lowercase						)
						SCREAMING_SNAKE_CASE							:    Optional[int]							=							[[False for _ in range(m + 1						)] for _ in range(n + 1						)]
						SCREAMING_SNAKE_CASE							:    Union[str, Any]							=							True
						for i in range(_lowercase						):
												for j in range(m + 1						):
																		if dp[i][j]:
																								if j < m and a[i].upper() == b[j]:
																														SCREAMING_SNAKE_CASE							:    List[str]							=							True
																								if a[i].islower():
																														SCREAMING_SNAKE_CASE							:    Dict							=							True
						return dp[n][m]


if __name__ == "__main__":
					import doctest

					doctest.testmod()





