
"""simple docstring"""



import math
def 					lowerCamelCase   (     ):
    UpperCAmelCase__	:      List[str]     							=					input('Enter message: ' )
    UpperCAmelCase__	:      List[Any]     							=					int(input(F'''Enter key [2-{len(A__ ) - 1}]: ''' ) )
    UpperCAmelCase__	:      Optional[int]     							=					input('Encryption/Decryption [e/d]: ' )

    if mode.lower().startswith('e' ):
        UpperCAmelCase__	:      Tuple     							=					encrypt_message(A__    ,A__ )
    elif mode.lower().startswith('d' ):
        UpperCAmelCase__	:      Union[str, Any]     							=					decrypt_message(A__    ,A__ )

    # Append pipe symbol (vertical bar) to identify spaces at the end.
    print(F'''Output:\n{text + '|'}''' )
def 					lowerCamelCase   (     _snake_case    ,_snake_case ):
    UpperCAmelCase__	:      List[Any]     							=					[''] * key
    for col in range(A__ ):
        UpperCAmelCase__	:      Optional[Any]     							=					col
        while pointer < len(A__ ):
            cipher_text[col] += message[pointer]
            pointer += key
    return "".join(A__ )
def 					lowerCamelCase   (     _snake_case    ,_snake_case ):
    UpperCAmelCase__	:      Optional[Any]     							=					math.ceil(len(A__ ) / key )
    UpperCAmelCase__	:      Tuple     							=					key
    UpperCAmelCase__	:      Optional[int]     							=					(num_cols * num_rows) - len(A__ )
    UpperCAmelCase__	:      List[Any]     							=					[''] * num_cols
    UpperCAmelCase__	:      str     							=					0
    UpperCAmelCase__	:      Tuple     							=					0

    for symbol in message:
        plain_text[col] += symbol
        col += 1

        if (
            (col == num_cols)
            or (col == num_cols - 1)
            and (row >= num_rows - num_shaded_boxes)
        ):
            UpperCAmelCase__	:      Any     							=					0
            row += 1

    return "".join(A__ )


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    main()




import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class 					__lowerCAmelCase	(   unittest.TestCase				):




  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






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




  @property
  def     A__	(							self   )    ->					Optional[int]:
        '''simple docstring'''






        _lowercase      			=1
        _lowercase      			=3
        _lowercase      			=(32, 32)

        _lowercase      			=floats_tensor((batch_size, num_channels) + sizes				,  rng=random.Random(0   )   ).to(lowerCAmelCase   )
        return image




  @property
  def     A__	(							self   )    ->					Union[str, Any]:
        '''simple docstring'''






        torch.manual_seed(0   )
        _lowercase      			=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				,  )
        return model




  @property
  def     A__	(							self   )    ->					List[str]:
        '''simple docstring'''






        torch.manual_seed(0   )
        _lowercase      			=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				,  )
        return model




  @property
  def     A__	(							self   )    ->					Dict:
        '''simple docstring'''






        torch.manual_seed(0   )
        _lowercase      			=RobertaSeriesConfig(
            hidden_size=32				,  project_dim=32				,  intermediate_size=37				,  layer_norm_eps=1e-05				,  num_attention_heads=4				,  num_hidden_layers=5				,  pad_token_id=1				,  vocab_size=5_006				,  )
        return RobertaSeriesModelWithTransformation(lowerCAmelCase   )




  @property
  def     A__	(							self   )    ->					Tuple:
        '''simple docstring'''






        def extract(*lowerCAmelCase				,  **lowerCAmelCase   ):





              class 					__lowerCAmelCase	:




                def __init__(							self   )    ->					Union[str, Any]:
                      '''simple docstring'''






                      _lowercase      			=torch.ones([0]   )




                def     A__	(							self				,  lowerCAmelCase   )    ->					Dict:
                      '''simple docstring'''






                      self.pixel_values.to(lowerCAmelCase   )
                      return self
              return Out()

        return extract




  def     A__	(							self   )    ->					int:
        '''simple docstring'''






        _lowercase      			='cpu'  # ensure determinism for the device-dependent torch.Generator
        _lowercase      			=self.dummy_cond_unet
        _lowercase      			=PNDMScheduler(skip_prk_steps=lowerCAmelCase   )
        _lowercase      			=self.dummy_vae
        _lowercase      			=self.dummy_text_encoder
        _lowercase      			=XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'   )
        _lowercase      			=77

        _lowercase      			=self.dummy_image.to(lowerCAmelCase   )
        _lowercase      			=init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        _lowercase      			=AltDiffusionImgaImgPipeline(
            unet=lowerCAmelCase				,  scheduler=lowerCAmelCase				,  vae=lowerCAmelCase				,  text_encoder=lowerCAmelCase				,  tokenizer=lowerCAmelCase				,  safety_checker=lowerCAmelCase				,  feature_extractor=self.dummy_extractor				,  )
        _lowercase      			=VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,  do_normalize=lowerCAmelCase   )
        _lowercase      			=alt_pipe.to(lowerCAmelCase   )
        alt_pipe.set_progress_bar_config(disable=lowerCAmelCase   )

        _lowercase      			='A painting of a squirrel eating a burger'
        _lowercase      			=torch.Generator(device=lowerCAmelCase   ).manual_seed(0   )
        _lowercase      			=alt_pipe(
            [prompt]				,  generator=lowerCAmelCase				,  guidance_scale=6.0				,  num_inference_steps=2				,  output_type='np'				,  image=lowerCAmelCase				,  )

        _lowercase      			=output.images

        _lowercase      			=torch.Generator(device=lowerCAmelCase   ).manual_seed(0   )
        _lowercase      			=alt_pipe(
            [prompt]				,  generator=lowerCAmelCase				,  guidance_scale=6.0				,  num_inference_steps=2				,  output_type='np'				,  image=lowerCAmelCase				,  return_dict=lowerCAmelCase				,  )[0]

        _lowercase      			=image[0, -3:, -3:, -1]
        _lowercase      			=image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)
        _lowercase      			=np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]   )

        assert np.abs(image_slice.flatten() - expected_slice   ).max() < 5e-3
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 5e-3




  @unittest.skipIf(torch_device != 'cuda'				,  'This test requires a GPU'   )
  def     A__	(							self   )    ->					Optional[Any]:
        '''simple docstring'''






        _lowercase      			=self.dummy_cond_unet
        _lowercase      			=PNDMScheduler(skip_prk_steps=lowerCAmelCase   )
        _lowercase      			=self.dummy_vae
        _lowercase      			=self.dummy_text_encoder
        _lowercase      			=XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'   )
        _lowercase      			=77

        _lowercase      			=self.dummy_image.to(lowerCAmelCase   )

        # put models in fp16
        _lowercase      			=unet.half()
        _lowercase      			=vae.half()
        _lowercase      			=bert.half()

        # make sure here that pndm scheduler skips prk
        _lowercase      			=AltDiffusionImgaImgPipeline(
            unet=lowerCAmelCase				,  scheduler=lowerCAmelCase				,  vae=lowerCAmelCase				,  text_encoder=lowerCAmelCase				,  tokenizer=lowerCAmelCase				,  safety_checker=lowerCAmelCase				,  feature_extractor=self.dummy_extractor				,  )
        _lowercase      			=VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor				,  do_normalize=lowerCAmelCase   )
        _lowercase      			=alt_pipe.to(lowerCAmelCase   )
        alt_pipe.set_progress_bar_config(disable=lowerCAmelCase   )

        _lowercase      			='A painting of a squirrel eating a burger'
        _lowercase      			=torch.manual_seed(0   )
        _lowercase      			=alt_pipe(
            [prompt]				,  generator=lowerCAmelCase				,  num_inference_steps=2				,  output_type='np'				,  image=lowerCAmelCase				,  ).images

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




  @unittest.skipIf(torch_device != 'cuda'				,  'This test requires a GPU'   )
  def     A__	(							self   )    ->					int:
        '''simple docstring'''






        _lowercase      			=load_image(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/img2img/sketch-mountains-input.jpg'   )
        # resize to resolution that is divisible by 8 but not 16 or 32
        _lowercase      			=init_image.resize((760, 504)   )

        _lowercase      			='BAAI/AltDiffusion'
        _lowercase      			=AltDiffusionImgaImgPipeline.from_pretrained(
            lowerCAmelCase				,  safety_checker=lowerCAmelCase				,  )
        pipe.to(lowerCAmelCase   )
        pipe.set_progress_bar_config(disable=lowerCAmelCase   )
        pipe.enable_attention_slicing()

        _lowercase      			='A fantasy landscape, trending on artstation'

        _lowercase      			=torch.manual_seed(0   )
        _lowercase      			=pipe(
            prompt=lowerCAmelCase				,  image=lowerCAmelCase				,  strength=0.75				,  guidance_scale=7.5				,  generator=lowerCAmelCase				,  output_type='np'				,  )
        _lowercase      			=output.images[0]

        _lowercase      			=image[255:258, 383:386, -1]

        assert image.shape == (504, 760, 3)
        _lowercase      			=np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]   )

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





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




  def     A__	(							self   )    ->					Union[str, Any]:
        '''simple docstring'''






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




  def     A__	(							self   )    ->					str:
        '''simple docstring'''






        _lowercase      			=load_image(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/img2img/sketch-mountains-input.jpg'   )
        _lowercase      			=init_image.resize((768, 512)   )
        _lowercase      			=load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'   )

        _lowercase      			='BAAI/AltDiffusion'
        _lowercase      			=AltDiffusionImgaImgPipeline.from_pretrained(
            lowerCAmelCase				,  safety_checker=lowerCAmelCase				,  )
        pipe.to(lowerCAmelCase   )
        pipe.set_progress_bar_config(disable=lowerCAmelCase   )
        pipe.enable_attention_slicing()

        _lowercase      			='A fantasy landscape, trending on artstation'

        _lowercase      			=torch.manual_seed(0   )
        _lowercase      			=pipe(
            prompt=lowerCAmelCase				,  image=lowerCAmelCase				,  strength=0.75				,  guidance_scale=7.5				,  generator=lowerCAmelCase				,  output_type='np'				,  )
        _lowercase      			=output.images[0]

        assert image.shape == (512, 768, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image   ).max() < 1e-2


