import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class       snake_case					(      _lowerCamelCase   ,						_lowerCamelCase   ,						unittest.TestCase						):
  lowercase_			=     StableDiffusionDiffEditPipeline
  lowercase_			=     TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
  lowercase_			=     TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
  lowercase_			=     frozenset(
      []						)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
  lowercase_			=     frozenset([]						)




  def 	__lowercase(      self     :	Optional[int]				)->       List[Any]:




       """simple docstring"""
       torch.manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		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     , attention_head_dim=(2, 4)     , use_linear_projection=A__     , )
       SCREAMING_SNAKE_CASE__				:				Any			=		DDIMScheduler(
           beta_start=0.0_0085     , beta_end=0.012     , beta_schedule='scaled_linear'     , clip_sample=A__     , set_alpha_to_one=A__     , )
       SCREAMING_SNAKE_CASE__				:				List[str]			=		DDIMInverseScheduler(
           beta_start=0.0_0085     , beta_end=0.012     , beta_schedule='scaled_linear'     , clip_sample=A__     , set_alpha_to_zero=A__     , )
       torch.manual_seed(0				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		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				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		CLIPTextConfig(
           bos_token_id=0     , eos_token_id=2     , hidden_size=32     , intermediate_size=37     , layer_norm_eps=1e-0_5     , num_attention_heads=4     , num_hidden_layers=5     , pad_token_id=1     , vocab_size=1000     , hidden_act='gelu'     , projection_dim=512     , )
       SCREAMING_SNAKE_CASE__				:				Dict			=		CLIPTextModel(A__				)
       SCREAMING_SNAKE_CASE__				:				Any			=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'				)

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		{
           'unet': unet,
           'scheduler': scheduler,
           'inverse_scheduler': inverse_scheduler,
           'vae': vae,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'safety_checker': None,
           'feature_extractor': None,
       }

       return components




  def 	__lowercase(      self     :	int     , a_     :	List[Any]     , a_     :	Optional[int]=0				)->       Tuple:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		floats_tensor((1, 16, 16)     , rng=random.Random(A__				)				).to(A__				)
       SCREAMING_SNAKE_CASE__				:				int			=		floats_tensor((1, 2, 4, 16, 16)     , rng=random.Random(A__				)				).to(A__				)
       if str(A__				).startswith('mps'				):
            SCREAMING_SNAKE_CASE__				:				int			=		torch.manual_seed(A__				)
       else:
            SCREAMING_SNAKE_CASE__				:				int			=		torch.Generator(device=A__				).manual_seed(A__				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		{
           'prompt': 'a dog and a newt',
           'mask_image': mask,
           'image_latents': latents,
           'generator': generator,
           'num_inference_steps': 2,
           'inpaint_strength': 1.0,
           'guidance_scale': 6.0,
           'output_type': 'numpy',
       }

       return inputs




  def 	__lowercase(      self     :	Dict     , a_     :	str     , a_     :	List[str]=0				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		floats_tensor((1, 3, 32, 32)     , rng=random.Random(A__				)				).to(A__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		image.cpu().permute(0     , 2     , 3     , 1				)[0]
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		Image.fromarray(np.uinta(A__				)				).convert('RGB'				)
       if str(A__				).startswith('mps'				):
            SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		torch.manual_seed(A__				)
       else:
            SCREAMING_SNAKE_CASE__				:				str			=		torch.Generator(device=A__				).manual_seed(A__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		{
           'image': image,
           'source_prompt': 'a cat and a frog',
           'target_prompt': 'a dog and a newt',
           'generator': generator,
           'num_inference_steps': 2,
           'num_maps_per_mask': 2,
           'mask_encode_strength': 1.0,
           'guidance_scale': 6.0,
           'output_type': 'numpy',
       }

       return inputs




  def 	__lowercase(      self     :	Any     , a_     :	Tuple     , a_     :	int=0				)->       str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Tuple			=		floats_tensor((1, 3, 32, 32)     , rng=random.Random(A__				)				).to(A__				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		image.cpu().permute(0     , 2     , 3     , 1				)[0]
       SCREAMING_SNAKE_CASE__				:				str			=		Image.fromarray(np.uinta(A__				)				).convert('RGB'				)
       if str(A__				).startswith('mps'				):
            SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		torch.manual_seed(A__				)
       else:
            SCREAMING_SNAKE_CASE__				:				int			=		torch.Generator(device=A__				).manual_seed(A__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		{
           'image': image,
           'prompt': 'a cat and a frog',
           'generator': generator,
           'num_inference_steps': 2,
           'inpaint_strength': 1.0,
           'guidance_scale': 6.0,
           'decode_latents': True,
           'output_type': 'numpy',
       }
       return inputs




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




       """simple docstring"""
       if not hasattr(self.pipeline_class     , '_optional_components'				):
            return

       SCREAMING_SNAKE_CASE__				:				str			=		self.get_dummy_components()
       SCREAMING_SNAKE_CASE__				:				str			=		self.pipeline_class(**A__				)
       pipe.to(A__				)
       pipe.set_progress_bar_config(disable=A__				)

       # set all optional components to None and update pipeline config accordingly
       for optional_component in pipe._optional_components:
            setattr(A__     , A__     , A__				)
       pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}				)

       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		self.get_dummy_inputs(A__				)
       SCREAMING_SNAKE_CASE__				:				Tuple			=		pipe(**A__				)[0]

       with tempfile.TemporaryDirectory() as tmpdir:
            pipe.save_pretrained(A__				)
            SCREAMING_SNAKE_CASE__				:				List[str]			=		self.pipeline_class.from_pretrained(A__				)
            pipe_loaded.to(A__				)
            pipe_loaded.set_progress_bar_config(disable=A__				)

       for optional_component in pipe._optional_components:
            self.assertTrue(
                getattr(A__     , A__				) is None     , F'''`{optional_component}` did not stay set to None after loading.'''     , )

       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.get_dummy_inputs(A__				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		pipe_loaded(**A__				)[0]

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		np.abs(output - output_loaded				).max()
       self.assertLess(A__     , 1e-4				)




  def 	__lowercase(      self     :	Dict				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		'cpu'

       SCREAMING_SNAKE_CASE__				:				int			=		self.get_dummy_components()
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		self.pipeline_class(**A__				)
       pipe.to(A__				)
       pipe.set_progress_bar_config(disable=A__				)

       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		self.get_dummy_mask_inputs(A__				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		pipe.generate_mask(**A__				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		mask[0, -3:, -3:]

       self.assertEqual(mask.shape     , (1, 16, 16)				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		np.array([0] * 9				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		np.abs(mask_slice.flatten() - expected_slice				).max()
       self.assertLessEqual(A__     , 1e-3				)
       self.assertEqual(mask[0, -3, -4]     , 0				)




  def 	__lowercase(      self     :	Optional[int]				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		'cpu'

       SCREAMING_SNAKE_CASE__				:				List[str]			=		self.get_dummy_components()
       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.pipeline_class(**A__				)
       pipe.to(A__				)
       pipe.set_progress_bar_config(disable=A__				)

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		self.get_dummy_inversion_inputs(A__				)
       SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		pipe.invert(**A__				).images
       SCREAMING_SNAKE_CASE__				:				Any			=		image[0, -1, -3:, -3:]

       self.assertEqual(image.shape     , (2, 32, 32, 3)				)
       SCREAMING_SNAKE_CASE__				:				List[str]			=		np.array(
           [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]     , )
       SCREAMING_SNAKE_CASE__				:				List[str]			=		np.abs(image_slice.flatten() - expected_slice				).max()
       self.assertLessEqual(A__     , 1e-3				)




  def 	__lowercase(      self     :	Tuple				)->       int:




       """simple docstring"""
       super().test_inference_batch_single_identical(expected_max_diff=5e-3				)




  def 	__lowercase(      self     :	Any				)->       int:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				str			=		'cpu'

       SCREAMING_SNAKE_CASE__				:				List[Any]			=		self.get_dummy_components()

       SCREAMING_SNAKE_CASE__				:				Any			=		{'beta_start': 0.0_0085, 'beta_end': 0.012, 'beta_schedule': 'scaled_linear'}
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		DPMSolverMultistepScheduler(**A__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		DPMSolverMultistepInverseScheduler(**A__				)

       SCREAMING_SNAKE_CASE__				:				Tuple			=		self.pipeline_class(**A__				)
       pipe.to(A__				)
       pipe.set_progress_bar_config(disable=A__				)

       SCREAMING_SNAKE_CASE__				:				Dict			=		self.get_dummy_inversion_inputs(A__				)
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		pipe.invert(**A__				).images
       SCREAMING_SNAKE_CASE__				:				Dict			=		image[0, -1, -3:, -3:]

       self.assertEqual(image.shape     , (2, 32, 32, 3)				)
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		np.array(
           [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.5_1050, 0.5015, 0.4407, 0.4799]     , )
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		np.abs(image_slice.flatten() - expected_slice				).max()
       self.assertLessEqual(A__     , 1e-3				)




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




  def 	__lowercase(      self     :	int				)->       List[str]:




       """simple docstring"""
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()




  @classmethod
  def 	__lowercase(      cls     :	Tuple				)->       Any:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[int]			=		load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png'				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		raw_image.convert('RGB'				).resize((768, 768)				)

       SCREAMING_SNAKE_CASE__				:				str			=		raw_image




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




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		torch.manual_seed(0				)

       SCREAMING_SNAKE_CASE__				:				Any			=		StableDiffusionDiffEditPipeline.from_pretrained(
           'stabilityai/stable-diffusion-2-1'     , safety_checker=A__     , torch_dtype=torch.floataa				)
       SCREAMING_SNAKE_CASE__				:				Dict			=		DDIMScheduler.from_config(pipe.scheduler.config				)
       SCREAMING_SNAKE_CASE__				:				int			=		DDIMInverseScheduler.from_config(pipe.scheduler.config				)
       pipe.enable_model_cpu_offload()
       pipe.set_progress_bar_config(disable=A__				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		'a bowl of fruit'
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		'a bowl of pears'

       SCREAMING_SNAKE_CASE__				:				List[Any]			=		pipe.generate_mask(
           image=self.raw_image     , source_prompt=A__     , target_prompt=A__     , generator=A__     , )

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		pipe.invert(
           prompt=A__     , image=self.raw_image     , inpaint_strength=0.7     , generator=A__				).latents

       SCREAMING_SNAKE_CASE__				:				int			=		pipe(
           prompt=A__     , mask_image=A__     , image_latents=A__     , generator=A__     , negative_prompt=A__     , inpaint_strength=0.7     , output_type='numpy'     , ).images[0]

       SCREAMING_SNAKE_CASE__				:				List[str]			=		(
           np.array(
               load_image(
                   'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                   '/diffedit/pears.png'				).resize((768, 768)				)				)
           / 255
       )
       assert np.abs((expected_image - image).max()				) < 5e-1




  def 	__lowercase(      self     :	List[str]				)->       List[Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__				:				Dict			=		torch.manual_seed(0				)

       SCREAMING_SNAKE_CASE__				:				int			=		StableDiffusionDiffEditPipeline.from_pretrained(
           'stabilityai/stable-diffusion-2-1'     , safety_checker=A__     , torch_dtype=torch.floataa				)
       SCREAMING_SNAKE_CASE__				:				List[Any]			=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config				)
       SCREAMING_SNAKE_CASE__				:				str			=		DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config				)
       pipe.enable_model_cpu_offload()
       pipe.set_progress_bar_config(disable=A__				)

       SCREAMING_SNAKE_CASE__				:				List[str]			=		'a bowl of fruit'
       SCREAMING_SNAKE_CASE__				:				int			=		'a bowl of pears'

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		pipe.generate_mask(
           image=self.raw_image     , source_prompt=A__     , target_prompt=A__     , generator=A__     , )

       SCREAMING_SNAKE_CASE__				:				Dict			=		pipe.invert(
           prompt=A__     , image=self.raw_image     , inpaint_strength=0.7     , generator=A__     , num_inference_steps=25     , ).latents

       SCREAMING_SNAKE_CASE__				:				int			=		pipe(
           prompt=A__     , mask_image=A__     , image_latents=A__     , generator=A__     , negative_prompt=A__     , inpaint_strength=0.7     , num_inference_steps=25     , output_type='numpy'     , ).images[0]

       SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		(
           np.array(
               load_image(
                   'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
                   '/diffedit/pears.png'				).resize((768, 768)				)				)
           / 255
       )
       assert np.abs((expected_image - image).max()				) < 5e-1




# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch

from accelerate import PartialState
from accelerate.utils.operations import broadcast, gather, gather_object, pad_across_processes, reduce







def     _a				(      lowercase__  :			Any ):







     '''simple docstring'''


     return (torch.arange(state.num_processes ) + 1.0 + (state.num_processes * state.process_index)).to(state.device )







def     _a				(      lowercase__  :			Tuple ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				int			=		create_tensor(lowercase__ )
     SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		gather(lowercase__ )
     assert gathered_tensor.tolist() == list(range(1     ,  state.num_processes**2 + 1 ) )







def     _a				(      lowercase__  :			List[Any] ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				str			=		[state.process_index]
     SCREAMING_SNAKE_CASE__				:				Any			=		gather_object(lowercase__ )
     assert len(lowercase__ ) == state.num_processes, f'''{gathered_obj}, {len(lowercase__ )} != {state.num_processes}'''
     assert gathered_obj == list(range(state.num_processes ) ), f'''{gathered_obj} != {list(range(state.num_processes ) )}'''







def     _a				(      lowercase__  :			str ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		create_tensor(lowercase__ )
     SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		broadcast(lowercase__ )
     assert broadcasted_tensor.shape == torch.Size([state.num_processes] )
     assert broadcasted_tensor.tolist() == list(range(1     ,  state.num_processes + 1 ) )







def     _a				(      lowercase__  :			int ):







     '''simple docstring'''


     if state.is_main_process:
          SCREAMING_SNAKE_CASE__				:				Optional[int]			=		torch.arange(state.num_processes + 1 ).to(state.device )
     else:
          SCREAMING_SNAKE_CASE__				:				List[Any]			=		torch.arange(state.num_processes ).to(state.device )
     SCREAMING_SNAKE_CASE__				:				Any			=		pad_across_processes(lowercase__ )
     assert padded_tensor.shape == torch.Size([state.num_processes + 1] )
     if not state.is_main_process:
          assert padded_tensor.tolist() == list(range(0     ,  state.num_processes ) ) + [0]







def     _a				(      lowercase__  :			Optional[Any] ):







     '''simple docstring'''


     if state.num_processes != 2:
          return
     SCREAMING_SNAKE_CASE__				:				List[Any]			=		create_tensor(lowercase__ )
     SCREAMING_SNAKE_CASE__				:				str			=		reduce(lowercase__     ,  'sum' )
     SCREAMING_SNAKE_CASE__				:				Union[str, Any]			=		torch.tensor([4.0, 6] ).to(state.device )
     assert torch.allclose(lowercase__     ,  lowercase__ ), f'''{reduced_tensor} != {truth_tensor}'''







def     _a				(      lowercase__  :			int ):







     '''simple docstring'''


     if state.num_processes != 2:
          return
     SCREAMING_SNAKE_CASE__				:				Any			=		create_tensor(lowercase__ )
     SCREAMING_SNAKE_CASE__				:				List[Any]			=		reduce(lowercase__     ,  'mean' )
     SCREAMING_SNAKE_CASE__				:				Optional[Any]			=		torch.tensor([2.0, 3] ).to(state.device )
     assert torch.allclose(lowercase__     ,  lowercase__ ), f'''{reduced_tensor} != {truth_tensor}'''







def     _a				(      lowercase__  :			int ):







     '''simple docstring'''


     main()







def     _a				(      ):







     '''simple docstring'''


     SCREAMING_SNAKE_CASE__				:				int			=		PartialState()
     state.print(f'''State: {state}''' )
     state.print('testing gather' )
     test_gather(lowercase__ )
     state.print('testing gather_object' )
     test_gather_object(lowercase__ )
     state.print('testing broadcast' )
     test_broadcast(lowercase__ )
     state.print('testing pad_across_processes' )
     test_pad_across_processes(lowercase__ )
     state.print('testing reduce_sum' )
     test_reduce_sum(lowercase__ )
     state.print('testing reduce_mean' )
     test_reduce_mean(lowercase__ )


if __name__ == "__main__":
      main()



