

'''simple docstring'''

import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class        A_ (				_UpperCamelCase       ,   _UpperCamelCase       ,   unittest.TestCase							):






     '''simple docstring'''



     UpperCAmelCase_						:	Union[str, Any]  		=  StableDiffusionXLImgaImgPipeline
     UpperCAmelCase_						:	int  		=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
     UpperCAmelCase_						:	Optional[Any]  		=  PipelineTesterMixin.required_optional_params - {"""latents"""}
     UpperCAmelCase_						:	List[Any]  		=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
     UpperCAmelCase_						:	str  		=  IMAGE_TO_IMAGE_IMAGE_PARAMS
     UpperCAmelCase_						:	Union[str, Any]  		=  IMAGE_TO_IMAGE_IMAGE_PARAMS


     def    UpperCAmelCase_       (		self :     str       )						->	Optional[int]:
      torch.manual_seed(0       )
      UpperCAmelCase       :	List[Any]											= 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')     ,			attention_head_dim=(2, 4)     ,			use_linear_projection=lowerCAmelCase_     ,			addition_embed_type='text_time'     ,			addition_time_embed_dim=8     ,			transformer_layers_per_block=(1, 2)     ,			projection_class_embeddings_input_dim=80     ,			cross_attention_dim=64     ,			)
      UpperCAmelCase       :	Union[str, Any]											= EulerDiscreteScheduler(
          beta_start=0.0_0085     ,			beta_end=0.012     ,			steps_offset=1     ,			beta_schedule='scaled_linear'     ,			timestep_spacing='leading'     ,			)
      torch.manual_seed(0       )
      UpperCAmelCase       :	Dict											= 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     ,			sample_size=128     ,			)
      torch.manual_seed(0       )
      UpperCAmelCase       :	Optional[int]											= CLIPTextConfig(
          bos_token_id=0     ,			eos_token_id=2     ,			hidden_size=32     ,			intermediate_size=37     ,			layer_norm_eps=1E-05     ,			num_attention_heads=4     ,			num_hidden_layers=5     ,			pad_token_id=1     ,			vocab_size=1_000     ,			hidden_act='gelu'     ,			projection_dim=32     ,			)
      UpperCAmelCase       :	int											= CLIPTextModel(lowerCAmelCase_       )
      UpperCAmelCase       :	int											= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     ,			local_files_only=lowerCAmelCase_       )

      UpperCAmelCase       :	Union[str, Any]											= CLIPTextModelWithProjection(lowerCAmelCase_       )
      UpperCAmelCase       :	Optional[int]											= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'     ,			local_files_only=lowerCAmelCase_       )

      UpperCAmelCase       :	Optional[Any]											= {
          'unet': unet,
          'scheduler': scheduler,
          'vae': vae,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'text_encoder_2': text_encoder_a,
          'tokenizer_2': tokenizer_a,
          # "safety_checker": None,
          # "feature_extractor": None,
      }
      return components


     def    UpperCAmelCase_       (		self :     str     ,			lowercase_ :     Optional[int]     ,			lowercase_ :     Union[str, Any]=0       )						->	Optional[Any]:
      UpperCAmelCase       :	Tuple											= floats_tensor((1, 3, 32, 32)     ,			rng=random.Random(lowerCAmelCase_       )       ).to(lowerCAmelCase_       )
      UpperCAmelCase       :	Union[str, Any]											= image / 2 + 0.5
      if str(lowerCAmelCase_       ).startswith('mps'       ):
       UpperCAmelCase       :	Any											= torch.manual_seed(lowerCAmelCase_       )
      else:
       UpperCAmelCase       :	Union[str, Any]											= torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
      UpperCAmelCase       :	int											= {
          'prompt': 'A painting of a squirrel eating a burger',
          'image': image,
          'generator': generator,
          'num_inference_steps': 2,
          'guidance_scale': 5.0,
          'output_type': 'numpy',
          'strength': 0.75,
      }
      return inputs


     def    UpperCAmelCase_       (		self :     Union[str, Any]       )						->	Tuple:
      UpperCAmelCase       :	List[Any]											= 'cpu'  # ensure determinism for the device-dependent torch.Generator
      UpperCAmelCase       :	int											= self.get_dummy_components()
      UpperCAmelCase       :	Union[str, Any]											= StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_       )
      UpperCAmelCase       :	Optional[Any]											= sd_pipe.to(lowerCAmelCase_       )
      sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

      UpperCAmelCase       :	Optional[int]											= self.get_dummy_inputs(lowerCAmelCase_       )
      UpperCAmelCase       :	Any											= sd_pipe(**lowerCAmelCase_       ).images
      UpperCAmelCase       :	Optional[Any]											= image[0, -3:, -3:, -1]

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

      UpperCAmelCase       :	Optional[Any]											= np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]       )

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


     def    UpperCAmelCase_       (		self :     Tuple       )						->	Optional[int]:
      super().test_attention_slicing_forward_pass(expected_max_diff=3E-3       )


     def    UpperCAmelCase_       (		self :     Optional[int]       )						->	Optional[Any]:
      super().test_inference_batch_single_identical(expected_max_diff=3E-3       )


     def    UpperCAmelCase_       (		self :     int       )						->	Any:
      pass




     def    UpperCAmelCase_       (		self :     Dict       )						->	Tuple:
      UpperCAmelCase       :	Tuple											= self.get_dummy_components()
      UpperCAmelCase       :	int											= StableDiffusionXLImgaImgPipeline(**lowerCAmelCase_       )
      UpperCAmelCase       :	int											= sd_pipe.to(lowerCAmelCase_       )
      UpperCAmelCase       :	int											= sd_pipe.to(lowerCAmelCase_       )
      sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

      # forward without prompt embeds
      UpperCAmelCase       :	Optional[Any]											= self.get_dummy_inputs(lowerCAmelCase_       )
      UpperCAmelCase       :	Optional[int]											= 3 * ['this is a negative prompt']
      UpperCAmelCase       :	List[Any]											= negative_prompt
      UpperCAmelCase       :	List[Any]											= 3 * [inputs['prompt']]

      UpperCAmelCase       :	List[str]											= sd_pipe(**lowerCAmelCase_       )
      UpperCAmelCase       :	Any											= output.images[0, -3:, -3:, -1]

      # forward with prompt embeds
      UpperCAmelCase       :	List[Any]											= self.get_dummy_inputs(lowerCAmelCase_       )
      UpperCAmelCase       :	Union[str, Any]											= 3 * ['this is a negative prompt']
      UpperCAmelCase       :	List[Any]											= 3 * [inputs.pop('prompt'       )]

      (
          (
          UpperCAmelCase	
      )					, (
          UpperCAmelCase	
      )					, (
          UpperCAmelCase	
      )					, (
          UpperCAmelCase	
      )					, 	
      )       :	List[str]											= sd_pipe.encode_prompt(lowerCAmelCase_     ,			negative_prompt=lowerCAmelCase_       )

      UpperCAmelCase       :	Optional[Any]											= sd_pipe(
          **lowerCAmelCase_     ,			prompt_embeds=lowerCAmelCase_     ,			negative_prompt_embeds=lowerCAmelCase_     ,			pooled_prompt_embeds=lowerCAmelCase_     ,			negative_pooled_prompt_embeds=lowerCAmelCase_     ,			)
      UpperCAmelCase       :	Dict											= output.images[0, -3:, -3:, -1]

      # make sure that it's equal
      assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1E-4




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






     '''simple docstring'''



     def    UpperCAmelCase_       (		self :     int       )						->	str:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()


     def    UpperCAmelCase_       (		self :     int     ,			lowercase_ :     str     ,			lowercase_ :     List[str]="cpu"     ,			lowercase_ :     Optional[Any]=torch.floataa     ,			lowercase_ :     List[Any]=0       )						->	str:
      UpperCAmelCase       :	List[str]											= torch.Generator(device=lowerCAmelCase_       ).manual_seed(lowerCAmelCase_       )
      UpperCAmelCase       :	Optional[Any]											= np.random.RandomState(lowerCAmelCase_       ).standard_normal((1, 4, 64, 64)       )
      UpperCAmelCase       :	str											= torch.from_numpy(lowerCAmelCase_       ).to(device=lowerCAmelCase_     ,			dtype=lowerCAmelCase_       )
      UpperCAmelCase       :	Optional[int]											= {
          'prompt': 'a photograph of an astronaut riding a horse',
          'latents': latents,
          'generator': generator,
          'num_inference_steps': 3,
          'guidance_scale': 7.5,
          'output_type': 'numpy',
      }
      return inputs




     def    UpperCAmelCase_       (		self :     Tuple       )						->	int:
      UpperCAmelCase       :	List[str]											= DiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-base'       )
      pipe.to(lowerCAmelCase_       )
      pipe.set_progress_bar_config(disable=lowerCAmelCase_       )

      UpperCAmelCase       :	Optional[Any]											= self.get_inputs(lowerCAmelCase_       )
      UpperCAmelCase       :	int											= pipe(**lowerCAmelCase_       ).images
      UpperCAmelCase       :	Dict											= image[0, -3:, -3:, -1].flatten()

      assert image.shape == (1, 512, 512, 3)
      UpperCAmelCase       :	int											= np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]       )
      assert np.abs(image_slice - expected_slice       ).max() < 7E-3











import importlib
import shutil
import threading
import warnings
from typing import List

import fsspec
import fsspec.asyn

from . import compression
from .hffilesystem import HfFileSystem


_snake_case  :    Tuple						    =  importlib.util.find_spec('s3fs') is not None

if _has_safs:
     from .safilesystem import SaFileSystem  # noqa: F401

_snake_case  :    List[compression.BaseCompressedFileFileSystem]						    =  [
    compression.BzaFileSystem,
    compression.GzipFileSystem,
    compression.LzaFileSystem,
    compression.XzFileSystem,
    compression.ZstdFileSystem,
]

# Register custom filesystems
for fs_class in COMPRESSION_FILESYSTEMS + [HfFileSystem]:
     if fs_class.protocol in fsspec.registry and fsspec.registry[fs_class.protocol] is not fs_class:
          warnings.warn(F"""A filesystem protocol was already set for {fs_class.protocol} and will be overwritten.""")
     fsspec.register_implementation(fs_class.protocol, fs_class, clobber=True)

def   a_    ( lowerCAmelCase_      :			str	):
   if "://" in dataset_path:
      __lowerCAmelCase								=	dataset_path.split('://'	)[1]
   return dataset_path

def   a_    ( lowerCAmelCase_      :			fsspec.AbstractFileSystem	):
   if fs is not None and fs.protocol != "file":
      return True
   else:
      return False

def   a_    ( lowerCAmelCase_      :			fsspec.AbstractFileSystem,	lowerCAmelCase_      :			str,	lowerCAmelCase_      :			str	):
   __lowerCAmelCase								=	not is_remote_filesystem(lowerCAmelCase_	)
   if is_local:
      # LocalFileSystem.mv does copy + rm, it is more efficient to simply move a local directory
      shutil.move(fs._strip_protocol(lowerCAmelCase_	),	fs._strip_protocol(lowerCAmelCase_	)	)
   else:
      fs.mv(lowerCAmelCase_,	lowerCAmelCase_,	recursive=lowerCAmelCase_	)




def   a_    ( ):
   if hasattr(fsspec.asyn,	'reset_lock'	):
      # for future fsspec>2022.05.0
      fsspec.asyn.reset_lock()
   else:
      __lowerCAmelCase								=	None
      __lowerCAmelCase								=	None
      __lowerCAmelCase								=	threading.Lock()

