



'''simple docstring'''





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 							lowerCAmelCase_		(	a_  ,      a_  ,      unittest.TestCase						):
    __UpperCAmelCase							=	StableDiffusionXLPipeline
    __UpperCAmelCase							=	TEXT_TO_IMAGE_PARAMS
    __UpperCAmelCase							=	TEXT_TO_IMAGE_BATCH_PARAMS
    __UpperCAmelCase							=	TEXT_TO_IMAGE_IMAGE_PARAMS
    __UpperCAmelCase							=	TEXT_TO_IMAGE_IMAGE_PARAMS





    def 					__snake_case       (    self    :    List[str]     ):



       '''simple docstring'''







       torch.manual_seed(0     )
       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'''),    attention_head_dim=(2, 4),    use_linear_projection=_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,    )
       snake_case   :							Dict						  =EulerDiscreteScheduler(
           beta_start=0.0_0085,    beta_end=0.012,    steps_offset=1,    beta_schedule='''scaled_linear''',    timestep_spacing='''leading''',    )
       torch.manual_seed(0     )
       snake_case   :							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,    sample_size=128,    )
       torch.manual_seed(0     )
       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=1_000,    hidden_act='''gelu''',    projection_dim=32,    )
       snake_case   :							Tuple						  =CLIPTextModel(_snake_case     )
       snake_case   :							Optional[Any]						  =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''',    local_files_only=_snake_case     )

       snake_case   :							Any						  =CLIPTextModelWithProjection(_snake_case     )
       snake_case   :							List[str]						  =CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''',    local_files_only=_snake_case     )

       snake_case   :							Dict						  ={
           '''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 					__snake_case       (    self    :    Any,    _snake_case    :    List[Any],    _snake_case    :    Optional[Any]=0     ):



       '''simple docstring'''







       if str(_snake_case     ).startswith('''mps'''     ):
          snake_case   :							List[str]						  =torch.manual_seed(_snake_case     )
       else:
          snake_case   :							Any						  =torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )
       snake_case   :							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 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       snake_case   :							Tuple						  ='''cpu'''  # ensure determinism for the device-dependent torch.Generator
       snake_case   :							Tuple						  =self.get_dummy_components()
       snake_case   :							List[str]						  =StableDiffusionXLPipeline(**_snake_case     )
       snake_case   :							Dict						  =sd_pipe.to(_snake_case     )
       sd_pipe.set_progress_bar_config(disable=_snake_case     )

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

       assert image.shape == (1, 64, 64, 3)
       snake_case   :							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 					__snake_case       (    self    :    Any     ):



       '''simple docstring'''







       snake_case   :							List[str]						  =self.get_dummy_components()
       snake_case   :							Optional[int]						  =StableDiffusionXLPipeline(**_snake_case     )
       snake_case   :							Tuple						  =sd_pipe.to(_snake_case     )
       snake_case   :							Dict						  =sd_pipe.to(_snake_case     )
       sd_pipe.set_progress_bar_config(disable=_snake_case     )

       # forward without prompt embeds
       snake_case   :							List[Any]						  =self.get_dummy_inputs(_snake_case     )
       snake_case   :							Any						  =3 * ['''this is a negative prompt''']
       snake_case   :							Optional[int]						  =negative_prompt
       snake_case   :							List[Any]						  =3 * [inputs['''prompt''']]

       snake_case   :							List[Any]						  =sd_pipe(**_snake_case     )
       snake_case   :							Dict						  =output.images[0, -3:, -3:, -1]

       # forward with prompt embeds
       snake_case   :							Union[str, Any]						  =self.get_dummy_inputs(_snake_case     )
       snake_case   :							Dict						  =3 * ['''this is a negative prompt''']
       snake_case   :							List[Any]						  =3 * [inputs.pop('''prompt'''     )]

       (
           (
           snake_case
       )  ,    (
           snake_case
       )  ,    (
           snake_case
       )  ,    (
           snake_case
       )  ,    
       )   :							Optional[int]						  =sd_pipe.encode_prompt(_snake_case,    negative_prompt=_snake_case     )

       snake_case   :							Optional[int]						  =sd_pipe(
           **_snake_case,    prompt_embeds=_snake_case,    negative_prompt_embeds=_snake_case,    pooled_prompt_embeds=_snake_case,    negative_pooled_prompt_embeds=_snake_case,    )
       snake_case   :							str						  =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 					__snake_case       (    self    :    Any     ):



       '''simple docstring'''







       super().test_attention_slicing_forward_pass(expected_max_diff=3E-3     )






    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       super().test_inference_batch_single_identical(expected_max_diff=3E-3     )





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





    def 					__snake_case       (    self    :    Optional[Any]     ):



       '''simple docstring'''







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





    def 					__snake_case       (    self    :    Optional[Any],    _snake_case    :    str,    _snake_case    :    Tuple="cpu",    _snake_case    :    Any=torch.floataa,    _snake_case    :    Optional[Any]=0     ):



       '''simple docstring'''







       snake_case   :							Optional[Any]						  =torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )
       snake_case   :							Tuple						  =np.random.RandomState(_snake_case     ).standard_normal((1, 4, 64, 64)     )
       snake_case   :							Tuple						  =torch.from_numpy(_snake_case     ).to(device=_snake_case,    dtype=_snake_case     )
       snake_case   :							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 					__snake_case       (    self    :    Tuple     ):



       '''simple docstring'''







       snake_case   :							Dict						  =DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base'''     )
       pipe.to(_snake_case     )
       pipe.set_progress_bar_config(disable=_snake_case     )

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

       assert image.shape == (1, 512, 512, 3)
       snake_case   :							Tuple						  =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










'''simple docstring'''





from __future__ import annotations

import random
import string





class 							lowerCAmelCase_		:





    def __init__(    self    :    Union[str, Any],    _snake_case    :    str | None = None     ):



       '''simple docstring'''







       snake_case   :							Optional[int]						  =passcode or self.__passcode_creator()
       snake_case   :							List[str]						  =self.__make_key_list()
       snake_case   :							Dict						  =self.__make_shift_key()





    def __str__(    self    :    List[Any]     ):



       '''simple docstring'''







       return "".join(self.__passcode     )





    def 					__snake_case       (    self    :    int,    _snake_case    :    list[int]     ):



       '''simple docstring'''







       for i in range(1,    len(_snake_case     ),    2     ):
          iterlist[i] *= -1
       return iterlist





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							int						  =string.ascii_letters + string.digits
       snake_case   :							Union[str, Any]						  =[random.choice(_snake_case     ) for _ in range(random.randint(10,    20     )     )]
       return password





    def 					__snake_case       (    self    :    Optional[int]     ):



       '''simple docstring'''







       snake_case   :							Dict						  =(
           string.ascii_letters + string.digits + string.punctuation + ''' \t\n'''
       )

       snake_case   :							Any						  =[]

       # creates points known as breakpoints to break the key_list_options at those
       # points and pivot each substring
       snake_case   :							Optional[int]						  =sorted(set(self.__passcode     )     )
       snake_case   :							list[str]						  =[]

       # algorithm for creating a new shuffled list, keys_l, out of key_list_options
       for i in key_list_options:
          temp_list.extend(_snake_case     )

          # checking breakpoints at which to pivot temporary sublist and add it into
          # keys_l
          if i in breakpoints or i == key_list_options[-1]:
             keys_l.extend(temp_list[::-1]     )
             temp_list.clear()

        # returning a shuffled keys_l to prevent brute force guessing of shift key
       return keys_l





    def 					__snake_case       (    self    :    Union[str, Any]     ):



       '''simple docstring'''







       snake_case   :							str						  =sum(self.__neg_pos([ord(_snake_case     ) for x in self.__passcode]     )     )
       return num if num > 0 else len(self.__passcode     )





    def 					__snake_case       (    self    :    Optional[int],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							List[Any]						  =''''''

       # decoding shift like Caesar cipher algorithm implementing negative shift or
       # reverse shift or left shift
       for i in encoded_message:
          snake_case   :							Optional[int]						  =self.__key_list.index(_snake_case     )
          decoded_message += self.__key_list[
              (position - self.__shift_key) % -len(self.__key_list     )
          ]

       return decoded_message






    def 					__snake_case       (    self    :    Union[str, Any],    _snake_case    :    str     ):



       '''simple docstring'''







       snake_case   :							int						  =''''''

       # encoding shift like Caesar cipher algorithm implementing positive shift or
       # forward shift or right shift
       for i in plaintext:
          snake_case   :							int						  =self.__key_list.index(_snake_case     )
          encoded_message += self.__key_list[
              (position + self.__shift_key) % len(self.__key_list     )
          ]

       return encoded_message




def 		_a   (  lowerCamelCase_ = "Hello, this is a modified Caesar cipher"							):
   snake_case   :							List[Any]						  =ShuffledShiftCipher()
   return cipa.decrypt(cipa.encrypt(lowerCamelCase_							)							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()





