





import gc
import unittest

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

from diffusers import TransformeraDModel, VQDiffusionPipeline, VQDiffusionScheduler, VQModel
from diffusers.pipelines.vq_diffusion.pipeline_vq_diffusion import LearnedClassifierFreeSamplingEmbeddings
from diffusers.utils import load_numpy, slow, torch_device
from diffusers.utils.testing_utils import require_torch_gpu


_UpperCamelCase				=       False




class  _lowerCamelCase       (			unittest.TestCase			):



      """simple docstring"""






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






        '''simple docstring'''






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







      @property
      def   UpperCAmelCase						(       self      )				->      Optional[int]:






        '''simple docstring'''






        return 12







      @property
      def   UpperCAmelCase						(       self      )				->      Tuple:






        '''simple docstring'''






        return 12







      @property
      def   UpperCAmelCase						(       self      )				->      Tuple:






        '''simple docstring'''






        return 32







      @property
      def   UpperCAmelCase						(       self      )				->      str:






        '''simple docstring'''






        torch.manual_seed(0      )
        __snake_case      : Optional[Any]						=				VQModel(
            block_out_channels=[32, 64] ,  in_channels=3 ,  out_channels=3 ,  down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] ,  up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] ,  latent_channels=3 ,  num_vq_embeddings=self.num_embed ,  vq_embed_dim=3 ,  )
        return model







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






        '''simple docstring'''






        __snake_case      : Optional[Any]						=				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      )
        return tokenizer







      @property
      def   UpperCAmelCase						(       self      )				->      Tuple:






        '''simple docstring'''






        torch.manual_seed(0      )
        __snake_case      : int						=				CLIPTextConfig(
            bos_token_id=0 ,  eos_token_id=2 ,  hidden_size=self.text_embedder_hidden_size ,  intermediate_size=37 ,  layer_norm_eps=1E-05 ,  num_attention_heads=4 ,  num_hidden_layers=5 ,  pad_token_id=1 ,  vocab_size=1000 ,  )
        return CLIPTextModel(_lowerCamelCase      )







      @property
      def   UpperCAmelCase						(       self      )				->      Dict:






        '''simple docstring'''






        torch.manual_seed(0      )

        __snake_case      : str						=				12
        __snake_case      : Optional[Any]						=				12

        __snake_case      : Dict						=				{
            '''attention_bias''': True,
            '''cross_attention_dim''': 32,
            '''attention_head_dim''': height * width,
            '''num_attention_heads''': 1,
            '''num_vector_embeds''': self.num_embed,
            '''num_embeds_ada_norm''': self.num_embeds_ada_norm,
            '''norm_num_groups''': 32,
            '''sample_size''': width,
            '''activation_fn''': '''geglu-approximate''',
        }

        __snake_case      : Dict						=				TransformeraDModel(**_lowerCamelCase      )
        return model







      def   UpperCAmelCase						(       self      )				->      Dict:






        '''simple docstring'''






        __snake_case      : Union[str, Any]						=				'''cpu'''

        __snake_case      : Optional[int]						=				self.dummy_vqvae
        __snake_case      : Any						=				self.dummy_text_encoder
        __snake_case      : Tuple						=				self.dummy_tokenizer
        __snake_case      : List[str]						=				self.dummy_transformer
        __snake_case      : str						=				VQDiffusionScheduler(self.num_embed      )
        __snake_case      : Optional[int]						=				LearnedClassifierFreeSamplingEmbeddings(learnable=_lowerCamelCase      )

        __snake_case      : Union[str, Any]						=				VQDiffusionPipeline(
            vqvae=_lowerCamelCase ,  text_encoder=_lowerCamelCase ,  tokenizer=_lowerCamelCase ,  transformer=_lowerCamelCase ,  scheduler=_lowerCamelCase ,  learned_classifier_free_sampling_embeddings=_lowerCamelCase ,  )
        __snake_case      : List[Any]						=				pipe.to(_lowerCamelCase      )
        pipe.set_progress_bar_config(disable=_lowerCamelCase      )

        __snake_case      : List[str]						=				'''teddy bear playing in the pool'''

        __snake_case      : Union[str, Any]						=				torch.Generator(device=_lowerCamelCase      ).manual_seed(0      )
        __snake_case      : List[str]						=				pipe([prompt] ,  generator=_lowerCamelCase ,  num_inference_steps=2 ,  output_type="np"      )
        __snake_case      : List[str]						=				output.images

        __snake_case      : List[Any]						=				torch.Generator(device=_lowerCamelCase      ).manual_seed(0      )
        __snake_case      : Any						=				pipe(
            [prompt] ,  generator=_lowerCamelCase ,  output_type="np" ,  return_dict=_lowerCamelCase ,  num_inference_steps=2      )[0]

        __snake_case      : List[Any]						=				image[0, -3:, -3:, -1]
        __snake_case      : Tuple						=				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 24, 24, 3)

        __snake_case      : int						=				np.array([0.6_551, 0.6_168, 0.5_008, 0.5_676, 0.5_659, 0.4_295, 0.6_073, 0.5_599, 0.4_992]      )

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







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






        '''simple docstring'''






        __snake_case      : List[str]						=				'''cpu'''

        __snake_case      : Union[str, Any]						=				self.dummy_vqvae
        __snake_case      : Optional[Any]						=				self.dummy_text_encoder
        __snake_case      : int						=				self.dummy_tokenizer
        __snake_case      : Optional[int]						=				self.dummy_transformer
        __snake_case      : Optional[int]						=				VQDiffusionScheduler(self.num_embed      )
        __snake_case      : str						=				LearnedClassifierFreeSamplingEmbeddings(
            learnable=_lowerCamelCase ,  hidden_size=self.text_embedder_hidden_size ,  length=tokenizer.model_max_length      )

        __snake_case      : Tuple						=				VQDiffusionPipeline(
            vqvae=_lowerCamelCase ,  text_encoder=_lowerCamelCase ,  tokenizer=_lowerCamelCase ,  transformer=_lowerCamelCase ,  scheduler=_lowerCamelCase ,  learned_classifier_free_sampling_embeddings=_lowerCamelCase ,  )
        __snake_case      : int						=				pipe.to(_lowerCamelCase      )
        pipe.set_progress_bar_config(disable=_lowerCamelCase      )

        __snake_case      : Optional[Any]						=				'''teddy bear playing in the pool'''

        __snake_case      : List[str]						=				torch.Generator(device=_lowerCamelCase      ).manual_seed(0      )
        __snake_case      : Tuple						=				pipe([prompt] ,  generator=_lowerCamelCase ,  num_inference_steps=2 ,  output_type="np"      )
        __snake_case      : Union[str, Any]						=				output.images

        __snake_case      : Union[str, Any]						=				torch.Generator(device=_lowerCamelCase      ).manual_seed(0      )
        __snake_case      : int						=				pipe(
            [prompt] ,  generator=_lowerCamelCase ,  output_type="np" ,  return_dict=_lowerCamelCase ,  num_inference_steps=2      )[0]

        __snake_case      : Union[str, Any]						=				image[0, -3:, -3:, -1]
        __snake_case      : List[str]						=				image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 24, 24, 3)

        __snake_case      : Optional[int]						=				np.array([0.6_693, 0.6_075, 0.4_959, 0.5_701, 0.5_583, 0.4_333, 0.6_171, 0.5_684, 0.4_988]      )

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




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



      """simple docstring"""






      def   UpperCAmelCase						(       self      )				->      Any:






        '''simple docstring'''






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







      def   UpperCAmelCase						(       self      )				->      Any:






        '''simple docstring'''






        __snake_case      : Optional[int]						=				load_numpy(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/vq_diffusion/teddy_bear_pool_classifier_free_sampling.npy"      )

        __snake_case      : Any						=				VQDiffusionPipeline.from_pretrained("microsoft/vq-diffusion-ithq"      )
        __snake_case      : List[Any]						=				pipeline.to(_lowerCamelCase      )
        pipeline.set_progress_bar_config(disable=_lowerCamelCase      )

        # requires GPU generator for gumbel softmax
        # don't use GPU generator in tests though
        __snake_case      : Dict						=				torch.Generator(device=_lowerCamelCase      ).manual_seed(0      )
        __snake_case      : Any						=				pipeline(
            "teddy bear playing in the pool" ,  num_images_per_prompt=1 ,  generator=_lowerCamelCase ,  output_type="np" ,  )

        __snake_case      : Union[str, Any]						=				output.images[0]

        assert image.shape == (256, 256, 3)
        assert np.abs(expected_image - image      ).max() < 2.0





import string

import numpy
def 				__lowerCamelCase						( UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		int						):




      """simple docstring"""





      return b if a == 0 else greatest_common_divisor(b % a ,  UpperCAmelCase_						)







class 		_snake_case  :
 SCREAMING_SNAKE_CASE__      =       string.ascii_uppercase + string.digits
 # This cipher takes alphanumerics into account
 # i.e. a total of 36 characters

 # take x and return x % len(key_string)
 SCREAMING_SNAKE_CASE__      =       numpy.vectorize(lambda _snake_case							: x % 36							)

 SCREAMING_SNAKE_CASE__      =       numpy.vectorize(_snake_case							)




 def __init__(		self					,  _lowerCamelCase    ):
       a						:List[Any] 							=       self.modulus(_lowerCamelCase    )  # mod36 calc's on the encrypt key
       self.check_determinant()  # validate the determinant of the encryption key
       a						:int 							=       encrypt_key.shape[0]




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       return self.key_string.index(_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       return self.key_string[round(_lowerCamelCase    )]




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:str 							=       round(numpy.linalg.det(self.encrypt_key    )    )

       if det < 0:
             a						:Any 							=       det % len(self.key_string    )

       a						:Dict 							=       len(self.key_string    )
       if greatest_common_divisor(_lowerCamelCase					,  len(self.key_string    )    ) != 1:
             a						:int 							=       (
                 F'''determinant modular {req_l} of encryption key({det}) '''
                 F'''is not co prime w.r.t {req_l}.\nTry another key.'''
             )
             raise ValueError(_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       a						:Optional[Any] 							=       [char for char in text.upper() if char in self.key_string]

       a						:List[str] 							=       chars[-1]
       while len(_lowerCamelCase    ) % self.break_key != 0:
             chars.append(_lowerCamelCase    )

       return "".join(_lowerCamelCase    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       a						:Dict 							=       self.process_text(text.upper()    )
       a						:List[str] 							=       ''''''

       for i in range(0					,  len(_lowerCamelCase    ) - self.break_key + 1					,  self.break_key    ):
             a						:int 							=       text[i : i + self.break_key]
             a						:Optional[int] 							=       [self.replace_letters(_lowerCamelCase    ) for char in batch]
             a						:Union[str, Any] 							=       numpy.array([vec]    ).T
             a						:str 							=       self.modulus(self.encrypt_key.dot(_lowerCamelCase    )    ).T.tolist()[
                 0
             ]
             a						:List[Any] 							=       ''''''.join(
                 self.replace_digits(_lowerCamelCase    ) for num in batch_encrypted    )
             encrypted += encrypted_batch

       return encrypted




 def        SCREAMING_SNAKE_CASE__				(		self    ):
       a						:List[Any] 							=       round(numpy.linalg.det(self.encrypt_key    )    )

       if det < 0:
             a						:int 							=       det % len(self.key_string    )
       a						:Tuple 							=       None
       for i in range(len(self.key_string    )    ):
             if (det * i) % len(self.key_string    ) == 1:
                   a						:Tuple 							=       i
                   break

       a						:List[str] 							=       (
           det_inv
           * numpy.linalg.det(self.encrypt_key    )
           * numpy.linalg.inv(self.encrypt_key    )
       )

       return self.to_int(self.modulus(_lowerCamelCase    )    )




 def        SCREAMING_SNAKE_CASE__				(		self					,  _lowerCamelCase    ):
       a						:List[Any] 							=       self.make_decrypt_key()
       a						:str 							=       self.process_text(text.upper()    )
       a						:List[Any] 							=       ''''''

       for i in range(0					,  len(_lowerCamelCase    ) - self.break_key + 1					,  self.break_key    ):
             a						:Optional[Any] 							=       text[i : i + self.break_key]
             a						:List[Any] 							=       [self.replace_letters(_lowerCamelCase    ) for char in batch]
             a						:str 							=       numpy.array([vec]    ).T
             a						:Dict 							=       self.modulus(decrypt_key.dot(_lowerCamelCase    )    ).T.tolist()[0]
             a						:List[Any] 							=       ''''''.join(
                 self.replace_digits(_lowerCamelCase    ) for num in batch_decrypted    )
             decrypted += decrypted_batch

       return decrypted







def 				__lowerCamelCase						( ):




      """simple docstring"""





      a						:Tuple 							=       int(input('''Enter the order of the encryption key: '''						)						)
      a						:Dict 							=       []

      print('''Enter each row of the encryption key with space separated integers'''						)
      for _ in range(UpperCAmelCase_						):
            a						:List[str] 							=       [int(UpperCAmelCase_						) for x in input().split()]
            hill_matrix.append(UpperCAmelCase_						)

      a						:Any 							=       HillCipher(numpy.array(UpperCAmelCase_						)						)

      print('''Would you like to encrypt or decrypt some text? (1 or 2)'''						)
      a						:Any 							=       input('''\n1. Encrypt\n2. Decrypt\n'''						)
      if option == "1":
            a						:str 							=       input('''What text would you like to encrypt?: '''						)
            print('''Your encrypted text is:'''						)
            print(hc.encrypt(UpperCAmelCase_						)						)
      elif option == "2":
            a						:Dict 							=       input('''What text would you like to decrypt?: '''						)
            print('''Your decrypted text is:'''						)
            print(hc.decrypt(UpperCAmelCase_						)						)


if __name__ == "__main__":
     import doctest

     doctest.testmod()

     main()





