


import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

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


enable_full_determinism()



class 							a       (      _UpperCAmelCase  ,_UpperCAmelCase  ,unittest.TestCase ):
     UpperCAmelCase__			:	Tuple       =						StableDiffusionXLPipeline
     UpperCAmelCase__			:	List[str]       =						TEXT_TO_IMAGE_PARAMS
     UpperCAmelCase__			:	str       =						TEXT_TO_IMAGE_BATCH_PARAMS
     UpperCAmelCase__			:	List[str]       =						TEXT_TO_IMAGE_IMAGE_PARAMS
     UpperCAmelCase__			:	Optional[Any]       =						TEXT_TO_IMAGE_IMAGE_PARAMS





     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[str]				):
        torch.manual_seed(0				)
        __lowerCamelCase:					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""")     ,						attention_head_dim=(2, 4)     ,						use_linear_projection=SCREAMING_SNAKE_CASE_     ,						addition_embed_type="""text_time"""     ,						addition_time_embed_dim=8     ,						transformer_layers_per_block=(1, 2)     ,						projection_class_embeddings_input_dim=80     ,						cross_attention_dim=64     ,						)
        __lowerCamelCase:					str	 =						EulerDiscreteScheduler(
            beta_start=0.0_0085     ,						beta_end=0.012     ,						steps_offset=1     ,						beta_schedule="""scaled_linear"""     ,						timestep_spacing="""leading"""     ,						)
        torch.manual_seed(0				)
        __lowerCamelCase:					Any	 =						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     ,						sample_size=128     ,						)
        torch.manual_seed(0				)
        __lowerCamelCase:					Dict	 =						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     ,						hidden_act="""gelu"""     ,						projection_dim=32     ,						)
        __lowerCamelCase:					List[str]	 =						CLIPTextModel(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     ,						local_files_only=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					List[Any]	 =						CLIPTextModelWithProjection(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[Any]	 =						CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     ,						local_files_only=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Optional[int]	 =						{
            """unet""": unet,
            """scheduler""": scheduler,
            """vae""": vae,
            """text_encoder""": text_encoder,
            """tokenizer""": tokenizer,
            """text_encoder_2""": text_encoder_a,
            """tokenizer_2""": tokenizer_a,
            # "safety_checker": None,
            # "feature_extractor": None,
        }
        return components





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]     ,						SCREAMING_SNAKE_CASE_       :					Any     ,						SCREAMING_SNAKE_CASE_       :					str=0				):
        if str(SCREAMING_SNAKE_CASE_				).startswith("""mps"""				):
           __lowerCamelCase:					Tuple	 =						torch.manual_seed(SCREAMING_SNAKE_CASE_				)
        else:
           __lowerCamelCase:					Any	 =						torch.Generator(device=SCREAMING_SNAKE_CASE_				).manual_seed(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Union[str, Any]	 =						{
            """prompt""": """A painting of a squirrel eating a burger""",
            """generator""": generator,
            """num_inference_steps""": 2,
            """guidance_scale""": 5.0,
            """output_type""": """numpy""",
        }
        return inputs





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Union[str, Any]				):
        __lowerCamelCase:					Optional[Any]	 =						"""cpu"""  # ensure determinism for the device-dependent torch.Generator
        __lowerCamelCase:					Any	 =						self.get_dummy_components()
        __lowerCamelCase:					Tuple	 =						StableDiffusionXLPipeline(**SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					str	 =						sd_pipe.to(SCREAMING_SNAKE_CASE_				)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					str	 =						self.get_dummy_inputs(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Optional[int]	 =						sd_pipe(**SCREAMING_SNAKE_CASE_				).images
        __lowerCamelCase:					int	 =						image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        __lowerCamelCase:					Optional[Any]	 =						np.array([0.5873, 0.6128, 0.4797, 0.5122, 0.5674, 0.4639, 0.5227, 0.5149, 0.4747]				)

        assert np.abs(image_slice.flatten() - expected_slice				).max() < 1E-2





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Dict				):
        __lowerCamelCase:					Tuple	 =						self.get_dummy_components()
        __lowerCamelCase:					int	 =						StableDiffusionXLPipeline(**SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					int	 =						sd_pipe.to(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					List[str]	 =						sd_pipe.to(SCREAMING_SNAKE_CASE_				)
        sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_				)

        # forward without prompt embeds
        __lowerCamelCase:					List[Any]	 =						self.get_dummy_inputs(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Tuple	 =						3 * ["""this is a negative prompt"""]
        __lowerCamelCase:					int	 =						negative_prompt
        __lowerCamelCase:					Optional[Any]	 =						3 * [inputs["""prompt"""]]

        __lowerCamelCase:					Any	 =						sd_pipe(**SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Tuple	 =						output.images[0, -3:, -3:, -1]

        # forward with prompt embeds
        __lowerCamelCase:					List[str]	 =						self.get_dummy_inputs(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					int	 =						3 * ["""this is a negative prompt"""]
        __lowerCamelCase:					Optional[int]	 =						3 * [inputs.pop("""prompt"""				)]

        (
            (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  (
            __lowerCamelCase
        ) ,  
        ):					Tuple	 =						sd_pipe.encode_prompt(SCREAMING_SNAKE_CASE_     ,						negative_prompt=SCREAMING_SNAKE_CASE_				)

        __lowerCamelCase:					Optional[Any]	 =						sd_pipe(
            **SCREAMING_SNAKE_CASE_     ,						prompt_embeds=SCREAMING_SNAKE_CASE_     ,						negative_prompt_embeds=SCREAMING_SNAKE_CASE_     ,						pooled_prompt_embeds=SCREAMING_SNAKE_CASE_     ,						negative_pooled_prompt_embeds=SCREAMING_SNAKE_CASE_     ,						)
        __lowerCamelCase:					Dict	 =						output.images[0, -3:, -3:, -1]

        # make sure that it's equal
        assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()				).max() < 1E-4





     def 			SCREAMING_SNAKE_CASE__							(     self       :					Optional[int]				):
        super().test_attention_slicing_forward_pass(expected_max_diff=3E-3				)







     def 			SCREAMING_SNAKE_CASE__							(     self       :					List[Any]				):
        super().test_inference_batch_single_identical(expected_max_diff=3E-3				)



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





     def 			SCREAMING_SNAKE_CASE__							(     self       :					str				):
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()





     def 			SCREAMING_SNAKE_CASE__							(     self       :					int     ,						SCREAMING_SNAKE_CASE_       :					int     ,						SCREAMING_SNAKE_CASE_       :					List[str]="cpu"     ,						SCREAMING_SNAKE_CASE_       :					str=torch.floataa     ,						SCREAMING_SNAKE_CASE_       :					Tuple=0				):
        __lowerCamelCase:					List[str]	 =						torch.Generator(device=SCREAMING_SNAKE_CASE_				).manual_seed(SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					Dict	 =						np.random.RandomState(SCREAMING_SNAKE_CASE_				).standard_normal((1, 4, 64, 64)				)
        __lowerCamelCase:					Dict	 =						torch.from_numpy(SCREAMING_SNAKE_CASE_				).to(device=SCREAMING_SNAKE_CASE_     ,						dtype=SCREAMING_SNAKE_CASE_				)
        __lowerCamelCase:					int	 =						{
            """prompt""": """a photograph of an astronaut riding a horse""",
            """latents""": latents,
            """generator""": generator,
            """num_inference_steps""": 3,
            """guidance_scale""": 7.5,
            """output_type""": """numpy""",
        }
        return inputs







     def 			SCREAMING_SNAKE_CASE__							(     self       :					Any				):
        __lowerCamelCase:					Optional[int]	 =						DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""				)
        pipe.to(SCREAMING_SNAKE_CASE_				)
        pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_				)

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

        assert image.shape == (1, 512, 512, 3)
        __lowerCamelCase:					List[str]	 =						np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]				)
        assert np.abs(image_slice - expected_slice				).max() < 7E-3






from string import ascii_uppercase



def      __lowerCAmelCase    (				snake_case						:     str    ,   snake_case						:     str    ,   snake_case						:     bool = False    ,   snake_case						:     str = ascii_uppercase			)							->				str:
   __lowerCamelCase:					List[str]	 =						keyword.upper()
   __lowerCamelCase:					Tuple	 =						plaintext.upper()
   __lowerCamelCase:					Optional[Any]	 =						set(snake_case			)

   # create a list of unique characters in the keyword - their order matters
   # it determines how we will map plaintext characters to the ciphertext
   __lowerCamelCase:					Tuple	 =						[]
   for char in keyword:
      if char in alphabet_set and char not in unique_chars:
         unique_chars.append(snake_case			)
    # the number of those unique characters will determine the number of rows
   __lowerCamelCase:					Tuple	 =						len(snake_case			)

   # create a shifted version of the alphabet
   __lowerCamelCase:					List[str]	 =						unique_chars + [
       char for char in alphabet if char not in unique_chars
   ]

   # create a modified alphabet by splitting the shifted alphabet into rows
   __lowerCamelCase:					List[str]	 =						[
       shifted_alphabet[k : k + num_unique_chars_in_keyword]
       for k in range(0    ,   26    ,   snake_case			)
   ]

   # map the alphabet characters to the modified alphabet characters
   # going 'vertically' through the modified alphabet - consider columns first
   __lowerCamelCase:					Union[str, Any]	 =						{}
   __lowerCamelCase:					str	 =						0
   for column in range(snake_case			):
      for row in modified_alphabet:
         # if current row (the last one) is too short, break out of loop
         if len(snake_case			) <= column:
            break

         # map current letter to letter in modified alphabet
         __lowerCamelCase:					Union[str, Any]	 =						row[column]
         letter_index += 1

   if verbose:
      print(snake_case			)
   # create the encrypted text by mapping the plaintext to the modified alphabet
   return "".join(mapping[char] if char in mapping else char for char in plaintext			)


if __name__ == "__main__":
   # example use
   print(mixed_keyword('''college''', '''UNIVERSITY'''))


