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


UpperCamelCase__											=   threading.Lock()
UpperCamelCase__											=   None

UpperCamelCase__											=   {
    "debug": logging.DEBUG,
    "info": logging.INFO,
    "warning": logging.WARNING,
    "error": logging.ERROR,
    "critical": logging.CRITICAL,
}

UpperCamelCase__											=   logging.WARNING

UpperCamelCase__											=   True




def   lowerCAmelCase_					(	)	->							Union[str, Any]:







      '''simple docstring'''


      UpperCAmelCase__								=    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_					(	)	->							str:







      '''simple docstring'''


      return __name__.split("."				)[0]




def   lowerCAmelCase_					(	)	->							logging.Logger:







      '''simple docstring'''


      return logging.getLogger(_get_library_name()				)




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      global _default_handler

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

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




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      global _default_handler

      with _lock:
            if not _default_handler:
                  return

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




def   lowerCAmelCase_					(	)	->							List[Any]:







      '''simple docstring'''


      return log_levels




def   lowerCAmelCase_					(	__A = None				)	->							logging.Logger:







      '''simple docstring'''


      if name is None:
            UpperCAmelCase__								=    _get_library_name()

      _configure_library_root_logger()
      return logging.getLogger(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							int:







      '''simple docstring'''


      _configure_library_root_logger()
      return _get_library_root_logger().getEffectiveLevel()




def   lowerCAmelCase_					(	__A				)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()
      _get_library_root_logger().setLevel(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							int:







      '''simple docstring'''


      return set_verbosity(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							Any:







      '''simple docstring'''


      return set_verbosity(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							Optional[Any]:







      '''simple docstring'''


      return set_verbosity(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							Any:







      '''simple docstring'''


      return set_verbosity(_UpperCamelCase				)




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()

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




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()

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




def   lowerCAmelCase_					(	__A				)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()

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




def   lowerCAmelCase_					(	__A				)	->							None:







      '''simple docstring'''


      _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_					(	)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()
      UpperCAmelCase__								=    False




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      _configure_library_root_logger()
      UpperCAmelCase__								=    True




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      UpperCAmelCase__								=    _get_library_root_logger().handlers

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




def   lowerCAmelCase_					(	)	->							None:







      '''simple docstring'''


      UpperCAmelCase__								=    _get_library_root_logger().handlers

      for handler in handlers:
            handler.setFormatter(_UpperCamelCase				)




def   lowerCAmelCase_					(	self,    *__A,    **__A				)	->							Optional[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=    os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS",    _UpperCamelCase				)
      if no_advisory_warnings:
            return
      self.warning(*_UpperCamelCase,    **_UpperCamelCase				)


UpperCamelCase__											=   warning_advice




@functools.lru_cache(_UpperCamelCase				)
def   lowerCAmelCase_					(	self,    *__A,    **__A				)	->							Union[str, Any]:







      '''simple docstring'''


      self.warning(*_UpperCamelCase,    **_UpperCamelCase				)


UpperCamelCase__											=   warning_once





class 	A				:


   def __init__(self	:		Optional[int]			,    *__UpperCAmelCase	:		List[Any]			,    **__UpperCAmelCase	:		Any						)		->							Any:  # pylint: disable=unused-argument
         """simple docstring"""



         UpperCAmelCase__								=    args[0] if args else None


   def __iter__(self	:		Any						)		->							List[Any]:
         """simple docstring"""



         return iter(self._iterator						)


   def __getattr__(self	:		List[str]			,    __UpperCAmelCase	:		List[Any]						)		->							Tuple:
         """simple docstring"""



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

         return empty_fn


   def __enter__(self	:		List[Any]						)		->							Tuple:
         """simple docstring"""



         return self





   def __exit__(self	:		int			,    __UpperCAmelCase	:		str			,    __UpperCAmelCase	:		List[Any]			,    __UpperCAmelCase	:		str						)		->							str:
         """simple docstring"""



         return





class 	A				:


   def __call__(self	:		Dict			,    *__UpperCAmelCase	:		Union[str, Any]			,    **__UpperCAmelCase	:		Dict						)		->							int:
         """simple docstring"""



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


   def      lowercase_ (self	:		List[Any]			,    *__UpperCAmelCase	:		List[str]			,    **__UpperCAmelCase	:		List[str]						)		->							str:
         """simple docstring"""



         UpperCAmelCase__								=    None
         if _tqdm_active:
               return tqdm_lib.tqdm.set_lock(*snake_case__			,    **snake_case__						)





   def      lowercase_ (self	:		Tuple						)		->							Optional[Any]:
         """simple docstring"""



         if _tqdm_active:
               return tqdm_lib.tqdm.get_lock()




UpperCamelCase__											=   _tqdm_cls()




def   lowerCAmelCase_					(	)	->							bool:







      '''simple docstring'''


      global _tqdm_active
      return bool(_tqdm_active				)




def   lowerCAmelCase_					(	)	->							Dict:







      '''simple docstring'''


      global _tqdm_active
      UpperCAmelCase__								=    True
      hf_hub_utils.enable_progress_bars()







def   lowerCAmelCase_					(	)	->							Any:







      '''simple docstring'''


      global _tqdm_active
      UpperCAmelCase__								=    False
      hf_hub_utils.disable_progress_bars()






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 UpperCamelCase      (      self			:   Optional[int]     ):

     """simple docstring"""






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

    @property
    def UpperCamelCase      (      self			:   Union[str, Any]     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      1
     SCREAMING_SNAKE_CASE		    =      3
     SCREAMING_SNAKE_CASE		    =      (3_2, 3_2)

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

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

     """simple docstring"""






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

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      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 UpperCamelCase      (      self			:   List[Any]     ):

     """simple docstring"""






     torch.manual_seed(0     )
     SCREAMING_SNAKE_CASE		    =      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(snake_case__     )

    @property
    def UpperCamelCase      (      self			:   Dict     ):

     """simple docstring"""






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




      class   UpperCamelCase			:

          def __init__(      self			:   str     ):

           """simple docstring"""






           SCREAMING_SNAKE_CASE		    =      torch.ones([0]     )




          def UpperCamelCase      (      self			:   Any				,     snake_case__			:   List[str]     ):

           """simple docstring"""






           self.pixel_values.to(snake_case__     )
           return self


      return Out()

     return extract

    def UpperCamelCase      (      self			:   Tuple     ):

     """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=snake_case__     )
     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		    =      7_7

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )
     SCREAMING_SNAKE_CASE		    =      init_image / 2 + 0.5

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

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

     SCREAMING_SNAKE_CASE		    =      output.images

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

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

     assert image.shape == (1, 3_2, 3_2, 3)
     SCREAMING_SNAKE_CASE		    =      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 UpperCamelCase      (      self			:   str     ):

     """simple docstring"""






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

     SCREAMING_SNAKE_CASE		    =      self.dummy_image.to(snake_case__     )

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

     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=snake_case__				,     num_inference_steps=2				,     output_type='np'				,     image=snake_case__				,     ).images

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




    @unittest.skipIf(torch_device != 'cuda'				,     'This test requires a GPU'     )
    def UpperCamelCase      (      self			:   Tuple     ):

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

     SCREAMING_SNAKE_CASE		    =      'BAAI/AltDiffusion'
     SCREAMING_SNAKE_CASE		    =      AltDiffusionImgaImgPipeline.from_pretrained(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     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=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      output.images[0]

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

     assert image.shape == (5_0_4, 7_6_0, 3)
     SCREAMING_SNAKE_CASE		    =      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 UpperCamelCase      (      self			:   int     ):

     """simple docstring"""






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




    def UpperCamelCase      (      self			:   List[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((7_6_8, 5_1_2)     )
     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(
         snake_case__				,     safety_checker=snake_case__				,     )
     pipe.to(snake_case__     )
     pipe.set_progress_bar_config(disable=snake_case__     )
     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=snake_case__				,     image=snake_case__				,     strength=0.75				,     guidance_scale=7.5				,     generator=snake_case__				,     output_type='np'				,     )
     SCREAMING_SNAKE_CASE		    =      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

