


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 						snake_case_     (       self:      int ):






            '''simple docstring'''




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







       @property
       def 						snake_case_     (       self:      Dict ):






            '''simple docstring'''




            __UpperCamelCase      =       1
            __UpperCamelCase      =       3
            __UpperCamelCase      =       (32, 32)

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







       @property
       def 						snake_case_     (       self:      List[Any] ):






            '''simple docstring'''




            torch.manual_seed(0 )
            __UpperCamelCase      =       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 						snake_case_     (       self:      str ):






            '''simple docstring'''




            torch.manual_seed(0 )
            __UpperCamelCase      =       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 						snake_case_     (       self:      Dict ):






            '''simple docstring'''




            torch.manual_seed(0 )
            __UpperCamelCase      =       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=5006,)
            return RobertaSeriesModelWithTransformation(__lowerCAmelCase )







       @property
       def 						snake_case_     (       self:      List[str] ):






            '''simple docstring'''




            def extract(*A_:      Any,**A_:      int ):



                 class      __lowerCamelCase       :







                        def __init__(       self:      Optional[int] ):






                             '''simple docstring'''




                             __UpperCamelCase      =       torch.ones([0] )







                        def 						snake_case_     (       self:      Tuple,A_:      str ):






                             '''simple docstring'''




                             self.pixel_values.to(__lowerCAmelCase )
                             return self



                 return Out()

            return extract







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






            '''simple docstring'''




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

            __UpperCamelCase      =       self.dummy_image.to(__lowerCAmelCase )
            __UpperCamelCase      =       init_image / 2 + 0.5

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

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

            __UpperCamelCase      =       output.images

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

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

            assert image.shape == (1, 32, 32, 3)
            __UpperCamelCase      =       np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9] )

            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 						snake_case_     (       self:      List[Any] ):






            '''simple docstring'''




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

            __UpperCamelCase      =       self.dummy_image.to(__lowerCAmelCase )

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

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

            __UpperCamelCase      =       'A painting of a squirrel eating a burger'
            __UpperCamelCase      =       torch.manual_seed(0 )
            __UpperCamelCase      =       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 						snake_case_     (       self:      Union[str, Any] ):






            '''simple docstring'''




            __UpperCamelCase      =       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
            __UpperCamelCase      =       init_image.resize((760, 504) )

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

            __UpperCamelCase      =       'A fantasy landscape, trending on artstation'

            __UpperCamelCase      =       torch.manual_seed(0 )
            __UpperCamelCase      =       pipe(
                prompt=__lowerCAmelCase,image=__lowerCAmelCase,strength=0.7_5,guidance_scale=7.5,generator=__lowerCAmelCase,output_type='np',)
            __UpperCamelCase      =       output.images[0]

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

            assert image.shape == (504, 760, 3)
            __UpperCamelCase      =       np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0] )

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



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







       def 						snake_case_     (       self:      str ):






            '''simple docstring'''




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







       def 						snake_case_     (       self:      str ):






            '''simple docstring'''




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

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

            __UpperCamelCase      =       'A fantasy landscape, trending on artstation'

            __UpperCamelCase      =       torch.manual_seed(0 )
            __UpperCamelCase      =       pipe(
                prompt=__lowerCAmelCase,image=__lowerCAmelCase,strength=0.7_5,guidance_scale=7.5,generator=__lowerCAmelCase,output_type='np',)
            __UpperCamelCase      =       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



'''simple docstring'''




import os
import string
import sys


__lowercase          =  1 << 8

__lowercase          =  {
    '''tab''': ord('''\t'''),
    '''newline''': ord('''\r'''),
    '''esc''': 2_7,
    '''up''': 6_5 + ARROW_KEY_FLAG,
    '''down''': 6_6 + ARROW_KEY_FLAG,
    '''right''': 6_7 + ARROW_KEY_FLAG,
    '''left''': 6_8 + ARROW_KEY_FLAG,
    '''mod_int''': 9_1,
    '''undefined''': sys.maxsize,
    '''interrupt''': 3,
    '''insert''': 5_0,
    '''delete''': 5_1,
    '''pg_up''': 5_3,
    '''pg_down''': 5_4,
}

__lowercase          =  KEYMAP['''up''']
__lowercase          =  KEYMAP['''left''']

if sys.platform == "win32":
						__lowercase          =  []
						__lowercase          =  {
						    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(1_0):
						__lowercase          =  ord(str(i))






def 				snake_case__							(			)    ->	List[Any]:

		'''simple docstring'''


		if os.name == "nt":
				import msvcrt

				lowerCAmelCase   					=  """mbcs"""
				# Flush the keyboard buffer
				while msvcrt.kbhit():
						msvcrt.getch()
				if len(_A ) == 0:
						# Read the keystroke
						lowerCAmelCase   					=  msvcrt.getch()

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

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






def 				snake_case__							(			)    ->	Tuple:

		'''simple docstring'''


		lowerCAmelCase   					=  get_raw_chars()
		if ord(_A ) in [KEYMAP["interrupt"], KEYMAP["newline"]]:
				return char

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

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




