

from importlib import import_module

from .logging import get_logger


a_     :    int     		=   get_logger(__name__)




class   UpperCamelCase			:

    def __init__(      self			:   Optional[int]				,     snake_case__			:   Any				,     snake_case__			:   Optional[int]=None     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      attrs or []
     if module is not None:
      for key in module.__dict__:
       if key in attrs or not key.startswith('__'     ):
        setattr(self				,     snake_case__				,     getattr(snake_case__				,     snake_case__     )     )
     SCREAMING_SNAKE_CASE		    =      module._original_module if isinstance(snake_case__				,     _PatchedModuleObj     ) else module




class   UpperCamelCase			:
    __UpperCamelCase    =[]

    def __init__(      self			:   List[Any]				,     snake_case__			:   Dict				,     snake_case__			:   str				,     snake_case__			:   Optional[Any]				,     snake_case__			:   Tuple=None     ):

     """simple docstring"""






     SCREAMING_SNAKE_CASE		    =      obj
     SCREAMING_SNAKE_CASE		    =      target
     SCREAMING_SNAKE_CASE		    =      new
     SCREAMING_SNAKE_CASE		    =      target.split('.'     )[0]
     SCREAMING_SNAKE_CASE		    =      {}
     SCREAMING_SNAKE_CASE		    =      attrs or []

    def __enter__(      self			:   Dict     ):

     """simple docstring"""






     *SCREAMING_SNAKE_CASE    ,						SCREAMING_SNAKE_CASE		    =      self.target.split('.'     )

     # Patch modules:
     # it's used to patch attributes of submodules like "os.path.join";
     # in this case we need to patch "os" and "os.path"

     for i in range(len(snake_case__     )     ):
      try:
       SCREAMING_SNAKE_CASE		    =      import_module('.'.join(submodules[: i + 1]     )     )
      except ModuleNotFoundError:
       continue
      # We iterate over all the globals in self.obj in case we find "os" or "os.path"
      for attr in self.obj.__dir__():
       SCREAMING_SNAKE_CASE		    =      getattr(self.obj				,     snake_case__     )
       # We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
       # This allows to patch renamed modules like "from os import path as ospath".
       if obj_attr is submodule or (
           (isinstance(snake_case__				,     _PatchedModuleObj     ) and obj_attr._original_module is submodule)
       ):
        SCREAMING_SNAKE_CASE		    =      obj_attr
        # patch at top level
        setattr(self.obj				,     snake_case__				,     _PatchedModuleObj(snake_case__				,     attrs=self.attrs     )     )
        SCREAMING_SNAKE_CASE		    =      getattr(self.obj				,     snake_case__     )
        # construct lower levels patches
        for key in submodules[i + 1 :]:
         setattr(snake_case__				,     snake_case__				,     _PatchedModuleObj(getattr(snake_case__				,     snake_case__				,     snake_case__     )				,     attrs=self.attrs     )     )
         SCREAMING_SNAKE_CASE		    =      getattr(snake_case__				,     snake_case__     )
        # finally set the target attribute
        setattr(snake_case__				,     snake_case__				,     self.new     )

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

     if submodules:  # if it's an attribute of a submodule like "os.path.join"
      try:
       SCREAMING_SNAKE_CASE		    =      getattr(import_module('.'.join(snake_case__     )     )				,     snake_case__     )
      except (AttributeError, ModuleNotFoundError):
       return
      # We iterate over all the globals in self.obj in case we find "os.path.join"
      for attr in self.obj.__dir__():
       # We don't check for the name of the global, but rather if its value *is* "os.path.join".
       # This allows to patch renamed attributes like "from os.path import join as pjoin".
       if getattr(self.obj				,     snake_case__     ) is attr_value:
        SCREAMING_SNAKE_CASE		    =      getattr(self.obj				,     snake_case__     )
        setattr(self.obj				,     snake_case__				,     self.new     )
     elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
      SCREAMING_SNAKE_CASE		    =      globals()['__builtins__'][target_attr]
      setattr(self.obj				,     snake_case__				,     self.new     )
     else:
      raise RuntimeError(F"""Tried to patch attribute {target_attr} instead of a submodule."""     )

    def __exit__(      self			:   Union[str, Any]				,     *snake_case__			:   Dict     ):

     """simple docstring"""






     for attr in list(self.original     ):
      setattr(self.obj				,     snake_case__				,     self.original.pop(snake_case__     )     )

    def UpperCamelCase      (      self			:   Tuple     ):

     """simple docstring"""






     self.__enter__()
     self._active_patches.append(self     )




    def UpperCamelCase      (      self			:   Any     ):

     """simple docstring"""






     try:
      self._active_patches.remove(self     )
     except ValueError:
      # If the patch hasn't been started this will fail
      return None

     return self.__exit__()




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

