


'''simple docstring'''







import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


@skip_mps
class 			__lowerCamelCase			(	a_    , unittest.TestCase	):
    """simple docstring"""
    a													=   VideoToVideoSDPipeline
    a													=   TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"video"}	) - {"image", "width", "height"}
    a													=   TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"video"}	) - {"image"}
    a													=   PipelineTesterMixin.required_optional_params - {"latents"}
    a													=   False

    # No `output_type`.
    a													=   frozenset(
        [
            "num_inference_steps",
            "generator",
            "latents",
            "return_dict",
            "callback",
            "callback_steps",
        ]	)


    def        A   (  self      :							Optional[Any]):
           torch.manual_seed(0)
           _A					:     Optional[int]     = UNetaDConditionModel(
               block_out_channels=(32, 64, 64, 64)				,							layers_per_block=2				,							sample_size=32				,							in_channels=4				,							out_channels=4				,							down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D')				,							up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D')				,							cross_attention_dim=32				,							attention_head_dim=4				,							)
           _A					:     Optional[int]     = DDIMScheduler(
               beta_start=0.0_0085				,							beta_end=0.012				,							beta_schedule='scaled_linear'				,							clip_sample=SCREAMING_SNAKE_CASE				,							set_alpha_to_one=SCREAMING_SNAKE_CASE				,							)
           torch.manual_seed(0)
           _A					:     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				,							sample_size=128				,							)
           torch.manual_seed(0)
           _A					:     int     = 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=1000				,							hidden_act='gelu'				,							projection_dim=512				,							)
           _A					:     Tuple     = CLIPTextModel(SCREAMING_SNAKE_CASE)
           _A					:     Optional[int]     = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

           _A					:     Any     = {
               'unet': unet,
               'scheduler': scheduler,
               'vae': vae,
               'text_encoder': text_encoder,
               'tokenizer': tokenizer,
           }
           return components


    def        A   (  self      :							int				,							SCREAMING_SNAKE_CASE      :							Dict				,							SCREAMING_SNAKE_CASE      :							List[Any]=0):
           # 3 frames
           _A					:     Optional[Any]     = floats_tensor((1, 3, 3, 32, 32)				,							rng=random.Random(SCREAMING_SNAKE_CASE)).to(SCREAMING_SNAKE_CASE)

           if str(SCREAMING_SNAKE_CASE).startswith('mps'):
                  _A					:     List[Any]     = torch.manual_seed(SCREAMING_SNAKE_CASE)
           else:
                  _A					:     Dict     = torch.Generator(device=SCREAMING_SNAKE_CASE).manual_seed(SCREAMING_SNAKE_CASE)
           _A					:     Tuple     = {
               'prompt': 'A painting of a squirrel eating a burger',
               'video': video,
               'generator': generator,
               'num_inference_steps': 2,
               'guidance_scale': 6.0,
               'output_type': 'pt',
           }
           return inputs


    def        A   (  self      :							List[str]):
           _A					:     Any     = 'cpu'  # ensure determinism for the device-dependent torch.Generator
           _A					:     Any     = self.get_dummy_components()
           _A					:     List[str]     = VideoToVideoSDPipeline(**SCREAMING_SNAKE_CASE)
           _A					:     Optional[int]     = sd_pipe.to(SCREAMING_SNAKE_CASE)
           sd_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE)

           _A					:     str     = self.get_dummy_inputs(SCREAMING_SNAKE_CASE)
           _A					:     Tuple     = 'np'
           _A					:     Dict     = sd_pipe(**SCREAMING_SNAKE_CASE).frames
           _A					:     Any     = frames[0][-3:, -3:, -1]

           assert frames[0].shape == (32, 32, 3)
           _A					:     Union[str, Any]     = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131])

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


    @unittest.skipIf(
        torch_device != 'cuda' or not is_xformers_available()				,							reason='XFormers attention is only available with CUDA and `xformers` installed'				,							)
    def        A   (  self      :							str):
           self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=SCREAMING_SNAKE_CASE				,							expected_max_diff=5e-3)


    @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.')
    def        A   (  self      :							Any):
           pass


    @unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.')
    def        A   (  self      :							Dict):
           pass


    @unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.')
    def        A   (  self      :							Any):
           pass


    def        A   (  self      :							Optional[Any]):
           return super().test_progress_bar()




@slow
@skip_mps
class 			__lowerCamelCase			(	unittest.TestCase	):
    """simple docstring"""


    def        A   (  self      :							Dict):
           _A					:     Dict     = VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'				,							torch_dtype=torch.floataa)
           pipe.enable_model_cpu_offload()

           # 10 frames
           _A					:     Any     = torch.Generator(device='cpu').manual_seed(0)
           _A					:     Dict     = torch.randn((1, 10, 3, 1024, 576)				,							generator=SCREAMING_SNAKE_CASE)
           _A					:     Union[str, Any]     = video.to('cuda')

           _A					:     str     = 'Spiderman is surfing'

           _A					:     str     = pipe(SCREAMING_SNAKE_CASE				,							video=SCREAMING_SNAKE_CASE				,							generator=SCREAMING_SNAKE_CASE				,							num_inference_steps=3				,							output_type='pt').frames

           _A					:     Tuple     = np.array([-1.045_8984, -1.127_9297, -0.966_3086, -0.9150_3906, -0.7509_7656])
           assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array).sum() < 1e-2










'''simple docstring'''







import string

import numpy






def 				lowerCAmelCase__	(    lowerCamelCase					:      int  ,lowerCamelCase					:      int       ):
       return b if a == 0 else greatest_common_divisor(b % a  ,lowerCamelCase       )


class 			__lowerCamelCase			:
    """simple docstring"""
    a													=   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)
    a													=   numpy.vectorize(lambda a_	: x % 36	)

    a													=   numpy.vectorize(a_	)


    def __init__(  self      :							List[Any]				,							SCREAMING_SNAKE_CASE      :							numpy.ndarray):
           _A					:     Union[str, Any]     = self.modulus(SCREAMING_SNAKE_CASE)  # mod36 calc's on the encrypt key
           self.check_determinant()  # validate the determinant of the encryption key
           _A					:     Optional[int]     = encrypt_key.shape[0]


    def        A   (  self      :							List[str]				,							SCREAMING_SNAKE_CASE      :							str):
           return self.key_string.index(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Union[str, Any]				,							SCREAMING_SNAKE_CASE      :							int):
           return self.key_string[round(SCREAMING_SNAKE_CASE)]


    def        A   (  self      :							List[Any]):
           _A					:     Optional[Any]     = round(numpy.linalg.det(self.encrypt_key))

           if det < 0:
                  _A					:     int     = det % len(self.key_string)

           _A					:     str     = len(self.key_string)
           if greatest_common_divisor(SCREAMING_SNAKE_CASE				,							len(self.key_string)) != 1:
                  _A					:     Optional[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(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							int				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     List[Any]     = [char for char in text.upper() if char in self.key_string]

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

           return "".join(SCREAMING_SNAKE_CASE)


    def        A   (  self      :							Optional[int]				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     Optional[int]     = self.process_text(text.upper())
           _A					:     List[str]     = ''

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

           return encrypted


    def        A   (  self      :							Union[str, Any]):
           _A					:     List[Any]     = round(numpy.linalg.det(self.encrypt_key))

           if det < 0:
                  _A					:     Optional[int]     = det % len(self.key_string)
           _A					:     List[str]     = None
           for i in range(len(self.key_string)):
                  if (det * i) % len(self.key_string) == 1:
                         _A					:     Union[str, Any]     = i
                         break

           _A					:     Dict     = (
               det_inv
               * numpy.linalg.det(self.encrypt_key)
               * numpy.linalg.inv(self.encrypt_key)
           )

           return self.to_int(self.modulus(SCREAMING_SNAKE_CASE))


    def        A   (  self      :							Any				,							SCREAMING_SNAKE_CASE      :							str):
           _A					:     List[str]     = self.make_decrypt_key()
           _A					:     Dict     = self.process_text(text.upper())
           _A					:     str     = ''

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

           return decrypted






def 				lowerCAmelCase__	(    ):
       _A					:     List[Any]     = int(input('Enter the order of the encryption key: '       )       )
       _A					:     List[str]     = []

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

       _A					:     Dict     = HillCipher(numpy.array(lowerCamelCase       )       )

       print('Would you like to encrypt or decrypt some text? (1 or 2)'       )
       _A					:     List[str]     = input('\n1. Encrypt\n2. Decrypt\n'       )
       if option == "1":
              _A					:     int     = input('What text would you like to encrypt?: '       )
              print('Your encrypted text is:'       )
              print(hc.encrypt(lowerCamelCase       )       )
       elif option == "2":
              _A					:     int     = input('What text would you like to decrypt?: '       )
              print('Your decrypted text is:'       )
              print(hc.decrypt(lowerCamelCase       )       )


if __name__ == "__main__":
   import doctest

   doctest.testmod()

   main()






