




import os
import string
import sys


lowerCamelCase__					:  Any      							=				1 << 8

lowerCamelCase__					:  Optional[int]      							=				{
    'tab': ord('\t'),
    'newline': ord('\r'),
    'esc': 27,
    'up': 65 + ARROW_KEY_FLAG,
    'down': 66 + ARROW_KEY_FLAG,
    'right': 67 + ARROW_KEY_FLAG,
    'left': 68 + ARROW_KEY_FLAG,
    'mod_int': 91,
    'undefined': sys.maxsize,
    'interrupt': 3,
    'insert': 50,
    'delete': 51,
    'pg_up': 53,
    'pg_down': 54,
}

lowerCamelCase__					:  Dict      							=				KEYMAP['up']
lowerCamelCase__					:  int      							=				KEYMAP['left']

if sys.platform == "win32":
   lowerCamelCase__					:  Any      							=				[]
   lowerCamelCase__					:  List[str]      							=				{
       b'\xe0H': KEYMAP['up'] - ARROW_KEY_FLAG,
       b'\x00H': KEYMAP['up'] - ARROW_KEY_FLAG,
       b'\xe0P': KEYMAP['down'] - ARROW_KEY_FLAG,
       b'\x00P': KEYMAP['down'] - ARROW_KEY_FLAG,
       b'\xe0M': KEYMAP['right'] - ARROW_KEY_FLAG,
       b'\x00M': KEYMAP['right'] - ARROW_KEY_FLAG,
       b'\xe0K': KEYMAP['left'] - ARROW_KEY_FLAG,
       b'\x00K': KEYMAP['left'] - ARROW_KEY_FLAG,
   }

for i in range(10):
   lowerCamelCase__					:  Union[str, Any]      							=				ord(str(i))

def    UpperCAmelCase_				( )   ->					Dict:
      if os.name == "nt":
            import msvcrt

            SCREAMING_SNAKE_CASE_      		=     'mbcs'
            # Flush the keyboard buffer
            while msvcrt.kbhit():
                  msvcrt.getch()
            if len(__UpperCAmelCase				) == 0:
                  # Read the keystroke
                  SCREAMING_SNAKE_CASE_      		=     msvcrt.getch()

                  # If it is a prefix char, get second part
                  if ch in (b"\x00", b"\xe0"):
                        SCREAMING_SNAKE_CASE_      		=     ch + msvcrt.getch()
                        # Translate actual Win chars to bullet char types
                        try:
                              SCREAMING_SNAKE_CASE_      		=     chr(WIN_KEYMAP[cha]				)
                              WIN_CH_BUFFER.append(chr(KEYMAP['mod_int']				)				)
                              WIN_CH_BUFFER.append(__UpperCAmelCase				)
                              if ord(__UpperCAmelCase				) in (
                                  KEYMAP["insert"] - 1 << 9,
                                  KEYMAP["delete"] - 1 << 9,
                                  KEYMAP["pg_up"] - 1 << 9,
                                  KEYMAP["pg_down"] - 1 << 9,
                              ):
                                    WIN_CH_BUFFER.append(chr(1_26				)				)
                              SCREAMING_SNAKE_CASE_      		=     chr(KEYMAP['esc']				)
                        except KeyError:
                              SCREAMING_SNAKE_CASE_      		=     cha[1]
                  else:
                        SCREAMING_SNAKE_CASE_      		=     ch.decode(__UpperCAmelCase				)
            else:
                  SCREAMING_SNAKE_CASE_      		=     WIN_CH_BUFFER.pop(0				)
      elif os.name == "posix":
            import termios
            import tty

            SCREAMING_SNAKE_CASE_      		=     sys.stdin.fileno()
            SCREAMING_SNAKE_CASE_      		=     termios.tcgetattr(__UpperCAmelCase				)
            try:
                  tty.setraw(__UpperCAmelCase				)
                  SCREAMING_SNAKE_CASE_      		=     sys.stdin.read(1				)
            finally:
                  termios.tcsetattr(__UpperCAmelCase     ,     termios.TCSADRAIN     ,     __UpperCAmelCase				)
      return ch





def    UpperCAmelCase_				( )   ->					List[str]:
      SCREAMING_SNAKE_CASE_      		=     get_raw_chars()
      if ord(__UpperCAmelCase				) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
            return char

      elif ord(__UpperCAmelCase				) == KEYMAP["esc"]:
            SCREAMING_SNAKE_CASE_      		=     get_raw_chars()
            if ord(__UpperCAmelCase				) == KEYMAP["mod_int"]:
                  SCREAMING_SNAKE_CASE_      		=     get_raw_chars()
                  if ord(__UpperCAmelCase				) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(__UpperCAmelCase				) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG:
                        return chr(ord(__UpperCAmelCase				) + ARROW_KEY_FLAG				)
                  else:
                        return KEYMAP["undefined"]
            else:
                  return get_raw_chars()

      else:
            if char in string.printable:
                  return char
            else:
                  return KEYMAP["undefined"]





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   ):


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       SCREAMING_SNAKE_CASE_      		=     1
       SCREAMING_SNAKE_CASE_      		=     3
       SCREAMING_SNAKE_CASE_      		=     (32, 32)

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



 @property
 def  lowerCAmelCase_    (				self    :						Union[str, Any]		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						Tuple		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						Optional[int]		):
       torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						List[Any]		):
       def extract(*_lowerCAmelCase    :						Optional[int]							,							**_lowerCAmelCase    :						str		):





             class 			lowerCamelCase_				:


              '''simple docstring'''







              def __init__(				self    :						str		):
                    SCREAMING_SNAKE_CASE_      		=     torch.ones([0]		)




              def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						int		):
                    self.pixel_values.to(_lowerCAmelCase		)
                    return self


             return Out()

       return extract



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       SCREAMING_SNAKE_CASE_      		=     'cpu'  # ensure determinism for the device-dependent torch.Generator
       SCREAMING_SNAKE_CASE_      		=     self.dummy_cond_unet
       SCREAMING_SNAKE_CASE_      		=     PNDMScheduler(skip_prk_steps=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.dummy_vae
       SCREAMING_SNAKE_CASE_      		=     self.dummy_text_encoder
       SCREAMING_SNAKE_CASE_      		=     XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'		)
       SCREAMING_SNAKE_CASE_      		=     77

       SCREAMING_SNAKE_CASE_      		=     self.dummy_image.to(_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     init_image / 2 + 0.5

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

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

       SCREAMING_SNAKE_CASE_      		=     output.images

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

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

       assert image.shape == (1, 32, 32, 3)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						Tuple		):
       SCREAMING_SNAKE_CASE_      		=     self.dummy_cond_unet
       SCREAMING_SNAKE_CASE_      		=     PNDMScheduler(skip_prk_steps=_lowerCAmelCase		)
       SCREAMING_SNAKE_CASE_      		=     self.dummy_vae
       SCREAMING_SNAKE_CASE_      		=     self.dummy_text_encoder
       SCREAMING_SNAKE_CASE_      		=     XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'		)
       SCREAMING_SNAKE_CASE_      		=     77

       SCREAMING_SNAKE_CASE_      		=     self.dummy_image.to(_lowerCAmelCase		)

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

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

       SCREAMING_SNAKE_CASE_      		=     'A painting of a squirrel eating a burger'
       SCREAMING_SNAKE_CASE_      		=     torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     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  lowerCAmelCase_    (				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     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
       SCREAMING_SNAKE_CASE_      		=     init_image.resize((760, 504)		)

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

       SCREAMING_SNAKE_CASE_      		=     'A fantasy landscape, trending on artstation'

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

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

       assert image.shape == (504, 760, 3)
       SCREAMING_SNAKE_CASE_      		=     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   ):


 '''simple docstring'''







 def  lowerCAmelCase_    (				self    :						str		):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




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

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

       SCREAMING_SNAKE_CASE_      		=     'A fantasy landscape, trending on artstation'

       SCREAMING_SNAKE_CASE_      		=     torch.manual_seed(0		)
       SCREAMING_SNAKE_CASE_      		=     pipe(
           prompt=_lowerCAmelCase							,							image=_lowerCAmelCase							,							strength=0.75							,							guidance_scale=7.5							,							generator=_lowerCAmelCase							,							output_type='np'							,							)
       SCREAMING_SNAKE_CASE_      		=     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