


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    UpperCAmelCase					(       unittest.TestCase    ):




			def   lowerCamelCase_					(						self							:		Optional[Any]						):







						"""simple docstring"""







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




			@property
			def   lowerCamelCase_					(						self							:		Optional[int]						):







						"""simple docstring"""







						UpperCamelCase         =					1
						UpperCamelCase         =					3
						UpperCamelCase         =					(3_2, 3_2)

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




			@property
			def   lowerCamelCase_					(						self							:		str						):







						"""simple docstring"""







						torch.manual_seed(0						)
						UpperCamelCase         =					UNetaDConditionModel(
						    block_out_channels=(3_2, 6_4)       ,       layers_per_block=2       ,       sample_size=3_2       ,       in_channels=4       ,       out_channels=4       ,       down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")       ,       up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")       ,       cross_attention_dim=3_2       ,       )
						return model




			@property
			def   lowerCamelCase_					(						self							:		Any						):







						"""simple docstring"""







						torch.manual_seed(0						)
						UpperCamelCase         =					AutoencoderKL(
						    block_out_channels=[3_2, 6_4]       ,       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							:		str						):







						"""simple docstring"""







						torch.manual_seed(0						)
						UpperCamelCase         =					RobertaSeriesConfig(
						    hidden_size=3_2       ,       project_dim=3_2       ,       intermediate_size=3_7       ,       layer_norm_eps=1e-05       ,       num_attention_heads=4       ,       num_hidden_layers=5       ,       pad_token_id=1       ,       vocab_size=5_0_0_6       ,       )
						return RobertaSeriesModelWithTransformation(__magic_name__						)




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







						"""simple docstring"""







						def extract(*__magic_name__							:		Union[str, Any]       ,       **__magic_name__							:		List[Any]						):




									class    UpperCAmelCase					:




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







															"""simple docstring"""







															UpperCamelCase         =					torch.ones([0]						)





												def   lowerCamelCase_					(						self							:		Any       ,       __magic_name__							:		List[Any]						):







															"""simple docstring"""







															self.pixel_values.to(__magic_name__						)
															return self


									return Out()

						return extract




			def   lowerCamelCase_					(						self							:		int						):







						"""simple docstring"""







						UpperCamelCase         =					"""cpu"""  # ensure determinism for the device-dependent torch.Generator
						UpperCamelCase         =					self.dummy_cond_unet
						UpperCamelCase         =					PNDMScheduler(skip_prk_steps=__magic_name__						)
						UpperCamelCase         =					self.dummy_vae
						UpperCamelCase         =					self.dummy_text_encoder
						UpperCamelCase         =					XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""						)
						UpperCamelCase         =					7_7

						UpperCamelCase         =					self.dummy_image.to(__magic_name__						)
						UpperCamelCase         =					init_image / 2 + 0.5

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

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

						UpperCamelCase         =					output.images

						UpperCamelCase         =					torch.Generator(device=__magic_name__						).manual_seed(0						)
						UpperCamelCase         =					alt_pipe(
						    [prompt]       ,       generator=__magic_name__       ,       guidance_scale=6.0       ,       num_inference_steps=2       ,       output_type="""np"""       ,       image=__magic_name__       ,       return_dict=__magic_name__       ,       )[0]

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

						assert image.shape == (1, 3_2, 3_2, 3)
						UpperCamelCase         =					np.array([0.4_427, 0.3_731, 0.4_249, 0.4_941, 0.4_546, 0.4_148, 0.4_193, 0.4_666, 0.4_499]						)

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







						"""simple docstring"""







						UpperCamelCase         =					self.dummy_cond_unet
						UpperCamelCase         =					PNDMScheduler(skip_prk_steps=__magic_name__						)
						UpperCamelCase         =					self.dummy_vae
						UpperCamelCase         =					self.dummy_text_encoder
						UpperCamelCase         =					XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""						)
						UpperCamelCase         =					7_7

						UpperCamelCase         =					self.dummy_image.to(__magic_name__						)

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

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

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

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





			@unittest.skipIf(torch_device != """cuda"""       ,       """This test requires a GPU"""						)
			def   lowerCamelCase_					(						self							:		Dict						):







						"""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((7_6_0, 5_0_4)						)

						UpperCamelCase         =					"""BAAI/AltDiffusion"""
						UpperCamelCase         =					AltDiffusionImgaImgPipeline.from_pretrained(
						    __magic_name__       ,       safety_checker=__magic_name__       ,       )
						pipe.to(__magic_name__						)
						pipe.set_progress_bar_config(disable=__magic_name__						)
						pipe.enable_attention_slicing()

						UpperCamelCase         =					"""A fantasy landscape, trending on artstation"""

						UpperCamelCase         =					torch.manual_seed(0						)
						UpperCamelCase         =					pipe(
						    prompt=__magic_name__       ,       image=__magic_name__       ,       strength=0.75       ,       guidance_scale=7.5       ,       generator=__magic_name__       ,       output_type="""np"""       ,       )
						UpperCamelCase         =					output.images[0]

						UpperCamelCase         =					image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

						assert image.shape == (5_0_4, 7_6_0, 3)
						UpperCamelCase         =					np.array([0.9_358, 0.9_397, 0.9_599, 0.9_901, 1.0_000, 1.0_000, 0.9_882, 1.0_000, 1.0_000]						)

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




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




			def   lowerCamelCase_					(						self							:		Tuple						):







						"""simple docstring"""







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





			def   lowerCamelCase_					(						self							:		List[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((7_6_8, 5_1_2)						)
						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(
						    __magic_name__       ,       safety_checker=__magic_name__       ,       )
						pipe.to(__magic_name__						)
						pipe.set_progress_bar_config(disable=__magic_name__						)
						pipe.enable_attention_slicing()

						UpperCamelCase         =					"""A fantasy landscape, trending on artstation"""

						UpperCamelCase         =					torch.manual_seed(0						)
						UpperCamelCase         =					pipe(
						    prompt=__magic_name__       ,       image=__magic_name__       ,       strength=0.75       ,       guidance_scale=7.5       ,       generator=__magic_name__       ,       output_type="""np"""       ,       )
						UpperCamelCase         =					output.images[0]

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








def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		int	):





			"""simple docstring"""




			UpperCamelCase         =					int(SCREAMING_SNAKE_CASE_	)
			if decimal in (0, 1):  # Exit cases for the recursion
						return str(SCREAMING_SNAKE_CASE_	)
			UpperCamelCase  ,  UpperCamelCase         =					divmod(SCREAMING_SNAKE_CASE_       ,  2	)
			return binary_recursive(SCREAMING_SNAKE_CASE_	) + str(SCREAMING_SNAKE_CASE_	)






def 							_lowercase    (		SCREAMING_SNAKE_CASE_   :		str	):





			"""simple docstring"""




			UpperCamelCase         =					str(SCREAMING_SNAKE_CASE_	).strip()
			if not number:
						raise ValueError("""No input value was provided"""	)
			UpperCamelCase         =					"""-""" if number.startswith("""-"""	) else """"""
			UpperCamelCase         =					number.lstrip("""-"""	)
			if not number.isnumeric():
						raise ValueError("""Input value is not an integer"""	)
			return f'{negative}0b{binary_recursive(int(SCREAMING_SNAKE_CASE_	)	)}'


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

			testmod()




