


'''simple docstring'''

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		:						int      )  ->			List[Any]:
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()







		@property
		def        __lowerCAmelCase		( self		:						List[str]      )  ->			Optional[int]:
			__magic_name__	:   Tuple					     =					1
			__magic_name__	:   Optional[int]					     =					3
			__magic_name__	:   Any					     =					(32, 32)

			__magic_name__	:   str					     =					floats_tensor((batch_size, num_channels) + sizes  ,					rng=random.Random(0      )      ).to(UpperCAmelCase_      )
			return image







		@property
		def        __lowerCAmelCase		( self		:						Dict      )  ->			Union[str, Any]:
			torch.manual_seed(0      )
			__magic_name__	:   int					     =					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		:						Dict      )  ->			List[str]:
			torch.manual_seed(0      )
			__magic_name__	:   Any					     =					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		:						List[Any]      )  ->			List[str]:
			torch.manual_seed(0      )
			__magic_name__	:   Dict					     =					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(UpperCAmelCase_      )







		@property
		def        __lowerCAmelCase		( self		:						List[str]      )  ->			Optional[Any]:
			def extract(*_A		:						List[str]  ,					**_A		:						Optional[int]      ):
				class _lowerCamelCase	:



						'''simple docstring'''







						def __init__( self		:						Dict      )  ->			Dict:
							__magic_name__	:   List[str]					     =					torch.ones([0]      )







						def        __lowerCAmelCase		( self		:						Optional[int]  ,					_A		:						Optional[int]      )  ->			str:
							self.pixel_values.to(UpperCAmelCase_      )
							return self







				return Out()

			return extract







		def        __lowerCAmelCase		( self		:						Dict      )  ->			Any:
			__magic_name__	:   Union[str, Any]					     =					"cpu"  # ensure determinism for the device-dependent torch.Generator
			__magic_name__	:   Dict					     =					self.dummy_cond_unet
			__magic_name__	:   Optional[int]					     =					PNDMScheduler(skip_prk_steps=UpperCAmelCase_      )
			__magic_name__	:   Optional[Any]					     =					self.dummy_vae
			__magic_name__	:   Tuple					     =					self.dummy_text_encoder
			__magic_name__	:   str					     =					XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'      )
			__magic_name__	:   List[Any]					     =					77

			__magic_name__	:   Union[str, Any]					     =					self.dummy_image.to(UpperCAmelCase_      )
			__magic_name__	:   List[str]					     =					init_image / 2 + 0.5

			# make sure here that pndm scheduler skips prk
			__magic_name__	:   List[str]					     =					AltDiffusionImgaImgPipeline(
			    unet=UpperCAmelCase_  ,					scheduler=UpperCAmelCase_  ,					vae=UpperCAmelCase_  ,					text_encoder=UpperCAmelCase_  ,					tokenizer=UpperCAmelCase_  ,					safety_checker=UpperCAmelCase_  ,					feature_extractor=self.dummy_extractor  ,					)
			__magic_name__	:   int					     =					VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor  ,					do_normalize=UpperCAmelCase_      )
			__magic_name__	:   List[Any]					     =					alt_pipe.to(UpperCAmelCase_      )
			alt_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

			__magic_name__	:   Tuple					     =					"A painting of a squirrel eating a burger"
			__magic_name__	:   Tuple					     =					torch.Generator(device=UpperCAmelCase_      ).manual_seed(0      )
			__magic_name__	:   List[Any]					     =					alt_pipe(
			    [prompt]  ,					generator=UpperCAmelCase_  ,					guidance_scale=6.0  ,					num_inference_steps=2  ,					output_type='np'  ,					image=UpperCAmelCase_  ,					)

			__magic_name__	:   List[Any]					     =					output.images

			__magic_name__	:   Tuple					     =					torch.Generator(device=UpperCAmelCase_      ).manual_seed(0      )
			__magic_name__	:   Optional[Any]					     =					alt_pipe(
			    [prompt]  ,					generator=UpperCAmelCase_  ,					guidance_scale=6.0  ,					num_inference_steps=2  ,					output_type='np'  ,					image=UpperCAmelCase_  ,					return_dict=UpperCAmelCase_  ,					)[0]

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

			assert image.shape == (1, 32, 32, 3)
			__magic_name__	:   Union[str, Any]					     =					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      )  ->			int:
			__magic_name__	:   Union[str, Any]					     =					self.dummy_cond_unet
			__magic_name__	:   Union[str, Any]					     =					PNDMScheduler(skip_prk_steps=UpperCAmelCase_      )
			__magic_name__	:   Union[str, Any]					     =					self.dummy_vae
			__magic_name__	:   Optional[int]					     =					self.dummy_text_encoder
			__magic_name__	:   int					     =					XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'      )
			__magic_name__	:   Any					     =					77

			__magic_name__	:   str					     =					self.dummy_image.to(UpperCAmelCase_      )

			# put models in fp16
			__magic_name__	:   Any					     =					unet.half()
			__magic_name__	:   int					     =					vae.half()
			__magic_name__	:   str					     =					bert.half()

			# make sure here that pndm scheduler skips prk
			__magic_name__	:   Optional[Any]					     =					AltDiffusionImgaImgPipeline(
			    unet=UpperCAmelCase_  ,					scheduler=UpperCAmelCase_  ,					vae=UpperCAmelCase_  ,					text_encoder=UpperCAmelCase_  ,					tokenizer=UpperCAmelCase_  ,					safety_checker=UpperCAmelCase_  ,					feature_extractor=self.dummy_extractor  ,					)
			__magic_name__	:   Tuple					     =					VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor  ,					do_normalize=UpperCAmelCase_      )
			__magic_name__	:   str					     =					alt_pipe.to(UpperCAmelCase_      )
			alt_pipe.set_progress_bar_config(disable=UpperCAmelCase_      )

			__magic_name__	:   Tuple					     =					"A painting of a squirrel eating a burger"
			__magic_name__	:   Dict					     =					torch.manual_seed(0      )
			__magic_name__	:   Any					     =					alt_pipe(
			    [prompt]  ,					generator=UpperCAmelCase_  ,					num_inference_steps=2  ,					output_type='np'  ,					image=UpperCAmelCase_  ,					).images

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







		@unittest.skipIf(torch_device != 'cuda'  ,					'This test requires a GPU'      )
		def        __lowerCAmelCase		( self		:						Dict      )  ->			Dict:
			__magic_name__	:   Union[str, Any]					     =					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
			__magic_name__	:   str					     =					init_image.resize((760, 504)      )

			__magic_name__	:   str					     =					"BAAI/AltDiffusion"
			__magic_name__	:   Optional[Any]					     =					AltDiffusionImgaImgPipeline.from_pretrained(
			    UpperCAmelCase_  ,					safety_checker=UpperCAmelCase_  ,					)
			pipe.to(UpperCAmelCase_      )
			pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
			pipe.enable_attention_slicing()

			__magic_name__	:   List[str]					     =					"A fantasy landscape, trending on artstation"

			__magic_name__	:   Any					     =					torch.manual_seed(0      )
			__magic_name__	:   Tuple					     =					pipe(
			    prompt=UpperCAmelCase_  ,					image=UpperCAmelCase_  ,					strength=0.75  ,					guidance_scale=7.5  ,					generator=UpperCAmelCase_  ,					output_type='np'  ,					)
			__magic_name__	:   str					     =					output.images[0]

			__magic_name__	:   Optional[Any]					     =					image[255:258, 383:386, -1]

			assert image.shape == (504, 760, 3)
			__magic_name__	:   List[Any]					     =					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		:						int      )  ->			Optional[int]:
			super().tearDown()
			gc.collect()
			torch.cuda.empty_cache()







		def        __lowerCAmelCase		( self		:						Dict      )  ->			Any:
			__magic_name__	:   Optional[Any]					     =					load_image(
			    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
			    '/img2img/sketch-mountains-input.jpg'      )
			__magic_name__	:   int					     =					init_image.resize((768, 512)      )
			__magic_name__	:   List[Any]					     =					load_numpy(
			    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'      )

			__magic_name__	:   int					     =					"BAAI/AltDiffusion"
			__magic_name__	:   str					     =					AltDiffusionImgaImgPipeline.from_pretrained(
			    UpperCAmelCase_  ,					safety_checker=UpperCAmelCase_  ,					)
			pipe.to(UpperCAmelCase_      )
			pipe.set_progress_bar_config(disable=UpperCAmelCase_      )
			pipe.enable_attention_slicing()

			__magic_name__	:   int					     =					"A fantasy landscape, trending on artstation"

			__magic_name__	:   Tuple					     =					torch.manual_seed(0      )
			__magic_name__	:   Union[str, Any]					     =					pipe(
			    prompt=UpperCAmelCase_  ,					image=UpperCAmelCase_  ,					strength=0.75  ,					guidance_scale=7.5  ,					generator=UpperCAmelCase_  ,					output_type='np'  ,					)
			__magic_name__	:   Optional[int]					     =					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'''

def lowerCamelCase      (      lowerCAmelCase    :     str		):





	"""simple docstring"""







	return "".join(chr(ord(lowerCAmelCase		) - 32		) if 'a' <= char <= 'z' else char for char in word		)


if __name__ == "__main__":
							from doctest import testmod

							testmod()