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




							def 	__snake_case(						self   :					Dict      )					->				Tuple:



												'''simple docstring'''

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




							@property
							def 	__snake_case(						self   :					Union[str, Any]      )					->				List[str]:



												'''simple docstring'''

												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(_UpperCamelCase      )
												return image




							@property
							def 	__snake_case(						self   :					Dict      )					->				int:



												'''simple docstring'''

												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 	__snake_case(						self   :					Tuple      )					->				Any:



												'''simple docstring'''

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



												'''simple docstring'''

												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(_UpperCamelCase      )




							@property
							def 	__snake_case(						self   :					Optional[Any]      )					->				Any:



												'''simple docstring'''

												def extract(*_UpperCamelCase   :					List[str]	,							**_UpperCamelCase   :					Dict      ):


																	class 						SCREAMING_SNAKE_CASE__    :




																								def __init__(						self   :					Optional[int]      )					->				int:



																													'''simple docstring'''

																													SCREAMING_SNAKE_CASE    			=       torch.ones([0]      )





																								def 	__snake_case(						self   :					List[str]	,							_UpperCamelCase   :					Optional[Any]      )					->				Optional[int]:



																													'''simple docstring'''

																													self.pixel_values.to(_UpperCamelCase      )
																													return self



																	return Out()

												return extract




							def 	__snake_case(						self   :					Dict      )					->				List[str]:



												'''simple docstring'''

												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=_UpperCamelCase      )
												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(_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       init_image / 2 + 0.5

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

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

												SCREAMING_SNAKE_CASE    			=       output.images

												SCREAMING_SNAKE_CASE    			=       torch.Generator(device=_UpperCamelCase      ).manual_seed(0      )
												SCREAMING_SNAKE_CASE    			=       alt_pipe(
												    [prompt]	,							generator=_UpperCamelCase	,							guidance_scale=6.0	,							num_inference_steps=2	,							output_type="np"	,							image=_UpperCamelCase	,							return_dict=_UpperCamelCase	,							)[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.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   :					Optional[Any]      )					->				Optional[Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.dummy_cond_unet
												SCREAMING_SNAKE_CASE    			=       PNDMScheduler(skip_prk_steps=_UpperCamelCase      )
												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(_UpperCamelCase      )

												# 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=_UpperCamelCase	,							scheduler=_UpperCamelCase	,							vae=_UpperCamelCase	,							text_encoder=_UpperCamelCase	,							tokenizer=_UpperCamelCase	,							safety_checker=_UpperCamelCase	,							feature_extractor=self.dummy_extractor	,							)
												SCREAMING_SNAKE_CASE    			=       VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor	,							do_normalize=_UpperCamelCase      )
												SCREAMING_SNAKE_CASE    			=       alt_pipe.to(_UpperCamelCase      )
												alt_pipe.set_progress_bar_config(disable=_UpperCamelCase      )

												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=_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 	__snake_case(						self   :					List[str]      )					->				Optional[Any]:



												'''simple docstring'''

												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(
												    _UpperCamelCase	,							safety_checker=_UpperCamelCase	,							)
												pipe.to(_UpperCamelCase      )
												pipe.set_progress_bar_config(disable=_UpperCamelCase      )
												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=_UpperCamelCase	,							image=_UpperCamelCase	,							strength=0.7_5	,							guidance_scale=7.5	,							generator=_UpperCamelCase	,							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.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 						SCREAMING_SNAKE_CASE__    (     unittest.TestCase     ):




							def 	__snake_case(						self   :					Tuple      )					->				Optional[int]:



												'''simple docstring'''

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





							def 	__snake_case(						self   :					str      )					->				Optional[Any]:



												'''simple docstring'''

												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(
												    _UpperCamelCase	,							safety_checker=_UpperCamelCase	,							)
												pipe.to(_UpperCamelCase      )
												pipe.set_progress_bar_config(disable=_UpperCamelCase      )
												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=_UpperCamelCase	,							image=_UpperCamelCase	,							strength=0.7_5	,							guidance_scale=7.5	,							generator=_UpperCamelCase	,							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





import functools
import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


_lowerCamelCase					:   str							=		threading.Lock()
_lowerCamelCase					:   Optional[logging.Handler]							=		None

_lowerCamelCase					:   Any							=		{
    '''debug''': logging.DEBUG,
    '''info''': logging.INFO,
    '''warning''': logging.WARNING,
    '''error''': logging.ERROR,
    '''critical''': logging.CRITICAL,
}

_lowerCamelCase					:   Union[str, Any]							=		logging.WARNING

_lowerCamelCase					:   List[Any]							=		True





def 	__lowerCamelCase							():
					SCREAMING_SNAKE_CASE    			=       os.getenv("TRANSFORMERS_VERBOSITY"      , UpperCAmelCase__  )
					if env_level_str:
										if env_level_str in log_levels:
															return log_levels[env_level_str]
										else:
															logging.getLogger().warning(
															    F"Unknown option TRANSFORMERS_VERBOSITY={env_level_str}, "
															    F"has to be one of: { ', '.join(log_levels.keys()  ) }"  )
					return _default_log_level





def 	__lowerCamelCase							():
					return __name__.split("."  )[0]





def 	__lowerCamelCase							():
					return logging.getLogger(_get_library_name()  )





def 	__lowerCamelCase							():
					global _default_handler

					with _lock:
										if _default_handler:
															# This library has already configured the library root logger.
															return
										SCREAMING_SNAKE_CASE    			=       logging.StreamHandler()  # Set sys.stderr as stream.
										SCREAMING_SNAKE_CASE    			=       sys.stderr.flush

										# Apply our default configuration to the library root logger.
										SCREAMING_SNAKE_CASE    			=       _get_library_root_logger()
										library_root_logger.addHandler(_default_handler  )
										library_root_logger.setLevel(_get_default_logging_level()  )
										SCREAMING_SNAKE_CASE    			=       False





def 	__lowerCamelCase							():
					global _default_handler

					with _lock:
										if not _default_handler:
															return

										SCREAMING_SNAKE_CASE    			=       _get_library_root_logger()
										library_root_logger.removeHandler(_default_handler  )
										library_root_logger.setLevel(logging.NOTSET  )
										SCREAMING_SNAKE_CASE    			=       None





def 	__lowerCamelCase							():
					return log_levels





def 	__lowerCamelCase							(UpperCAmelCase__     :							Optional[str] = None  ):

					if name is None:
										SCREAMING_SNAKE_CASE    			=       _get_library_name()

					_configure_library_root_logger()
					return logging.getLogger(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					_configure_library_root_logger()
					return _get_library_root_logger().getEffectiveLevel()





def 	__lowerCamelCase							(UpperCAmelCase__     :							int  ):
					_configure_library_root_logger()
					_get_library_root_logger().setLevel(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					return set_verbosity(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					return set_verbosity(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					return set_verbosity(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					return set_verbosity(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					_configure_library_root_logger()

					assert _default_handler is not None
					_get_library_root_logger().removeHandler(_default_handler  )





def 	__lowerCamelCase							():
					_configure_library_root_logger()

					assert _default_handler is not None
					_get_library_root_logger().addHandler(_default_handler  )





def 	__lowerCamelCase							(UpperCAmelCase__     :							logging.Handler  ):
					_configure_library_root_logger()

					assert handler is not None
					_get_library_root_logger().addHandler(UpperCAmelCase__  )





def 	__lowerCamelCase							(UpperCAmelCase__     :							logging.Handler  ):
					_configure_library_root_logger()

					assert handler is not None and handler not in _get_library_root_logger().handlers
					_get_library_root_logger().removeHandler(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					_configure_library_root_logger()
					SCREAMING_SNAKE_CASE    			=       False





def 	__lowerCamelCase							():
					_configure_library_root_logger()
					SCREAMING_SNAKE_CASE    			=       True





def 	__lowerCamelCase							():
					SCREAMING_SNAKE_CASE    			=       _get_library_root_logger().handlers

					for handler in handlers:
										SCREAMING_SNAKE_CASE    			=       logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s"  )
										handler.setFormatter(UpperCAmelCase__  )





def 	__lowerCamelCase							():
					SCREAMING_SNAKE_CASE    			=       _get_library_root_logger().handlers

					for handler in handlers:
										handler.setFormatter(UpperCAmelCase__  )





def 	__lowerCamelCase							(self     :							str      , *UpperCAmelCase__     :							Union[str, Any]      , **UpperCAmelCase__     :							List[str]  ):
					SCREAMING_SNAKE_CASE    			=       os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS"      , UpperCAmelCase__  )
					if no_advisory_warnings:
										return
					self.warning(*UpperCAmelCase__      , **UpperCAmelCase__  )


_lowerCamelCase					:   str							=		warning_advice





@functools.lru_cache(UpperCAmelCase__  )
def 	__lowerCamelCase							(self     :							List[str]      , *UpperCAmelCase__     :							Tuple      , **UpperCAmelCase__     :							int  ):
					self.warning(*UpperCAmelCase__      , **UpperCAmelCase__  )


_lowerCamelCase					:   Dict							=		warning_once


class 						lowercase    :




							def __init__(						self   :					List[Any]	,							*_UpperCamelCase   :					Union[str, Any]	,							**_UpperCamelCase   :					str      )					->				List[Any]:  # pylint: disable=unused-argument



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       args[0] if args else None




							def __iter__(						self   :					Optional[Any]      )					->				str:



												'''simple docstring'''

												return iter(self._iterator      )




							def __getattr__(						self   :					List[str]	,							_UpperCamelCase   :					Any      )					->				List[Any]:



												'''simple docstring'''

												def empty_fn(*_UpperCamelCase   :					List[str]	,							**_UpperCamelCase   :					Union[str, Any]      ):  # pylint: disable=unused-argument
																	return

												return empty_fn




							def __enter__(						self   :					Any      )					->				Optional[Any]:



												'''simple docstring'''

												return self





							def __exit__(						self   :					Optional[Any]	,							_UpperCamelCase   :					Tuple	,							_UpperCamelCase   :					str	,							_UpperCamelCase   :					List[str]      )					->				Union[str, Any]:



												'''simple docstring'''

												return



class 						lowercase    :




							def __call__(						self   :					Union[str, Any]	,							*_UpperCamelCase   :					Optional[Any]	,							**_UpperCamelCase   :					Tuple      )					->				Tuple:



												'''simple docstring'''

												if _tqdm_active:
																	return tqdm_lib.tqdm(*_UpperCamelCase	,							**_UpperCamelCase      )
												else:
																	return EmptyTqdm(*_UpperCamelCase	,							**_UpperCamelCase      )




							def 	__snake_case(						self   :					Dict	,							*_UpperCamelCase   :					Dict	,							**_UpperCamelCase   :					Union[str, Any]      )					->				Union[str, Any]:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       None
												if _tqdm_active:
																	return tqdm_lib.tqdm.set_lock(*_UpperCamelCase	,							**_UpperCamelCase      )





							def 	__snake_case(						self   :					Optional[int]      )					->				Union[str, Any]:



												'''simple docstring'''

												if _tqdm_active:
																	return tqdm_lib.tqdm.get_lock()



_lowerCamelCase					:   Union[str, Any]							=		_tqdm_cls()





def 	__lowerCamelCase							():
					global _tqdm_active
					return bool(_tqdm_active  )





def 	__lowerCamelCase							():
					global _tqdm_active
					SCREAMING_SNAKE_CASE    			=       True
					hf_hub_utils.enable_progress_bars()





def 	__lowerCamelCase							():
					global _tqdm_active
					SCREAMING_SNAKE_CASE    			=       False
					hf_hub_utils.disable_progress_bars()




