
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 (						UpperCAmelCase_	,    UpperCAmelCase_	,    unittest.TestCase				):
 __lowerCAmelCase	:  Optional[Any]	   =      StableDiffusionDiffEditPipeline
 __lowerCAmelCase	:  Tuple	   =      TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'height', 'width', 'image'} | {'image_latents'}
 __lowerCAmelCase	:  List[Any]	   =      TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {'image'} | {'image_latents'}
 __lowerCAmelCase	:  Any	   =      frozenset(
     []				)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
 __lowerCAmelCase	:  Optional[Any]	   =      frozenset([]				)


 def   lowercase__  (       self):


   '''simple docstring'''




   torch.manual_seed(0)
   lowercase__	: List[str]     		=   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=SCREAMING_SNAKE_CASE_       ,	)
   lowercase__	: Union[str, Any]     		=   DDIMScheduler(
       beta_start=0.0_0_0_8_5       ,	beta_end=0.0_1_2       ,	beta_schedule="""scaled_linear"""       ,	clip_sample=SCREAMING_SNAKE_CASE_       ,	set_alpha_to_one=SCREAMING_SNAKE_CASE_       ,	)
   lowercase__	: Optional[int]     		=   DDIMInverseScheduler(
       beta_start=0.0_0_0_8_5       ,	beta_end=0.0_1_2       ,	beta_schedule="""scaled_linear"""       ,	clip_sample=SCREAMING_SNAKE_CASE_       ,	set_alpha_to_zero=SCREAMING_SNAKE_CASE_       ,	)
   torch.manual_seed(0)
   lowercase__	: List[str]     		=   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=1_28       ,	)
   torch.manual_seed(0)
   lowercase__	: Tuple     		=   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=10_00       ,	hidden_act="""gelu"""       ,	projection_dim=5_12       ,	)
   lowercase__	: int     		=   CLIPTextModel(SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

   lowercase__	: Any     		=   {
       """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       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   floats_tensor((1, 16, 16)       ,	rng=random.Random(SCREAMING_SNAKE_CASE_)).to(SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   floats_tensor((1, 2, 4, 16, 16)       ,	rng=random.Random(SCREAMING_SNAKE_CASE_)).to(SCREAMING_SNAKE_CASE_)
   if str(SCREAMING_SNAKE_CASE_).startswith("""mps"""):
     lowercase__	: Union[str, Any]     		=   torch.manual_seed(SCREAMING_SNAKE_CASE_)
   else:
     lowercase__	: Optional[Any]     		=   torch.Generator(device=SCREAMING_SNAKE_CASE_).manual_seed(SCREAMING_SNAKE_CASE_)
   lowercase__	: Any     		=   {
       """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       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0):


   '''simple docstring'''




   lowercase__	: Optional[int]     		=   floats_tensor((1, 3, 32, 32)       ,	rng=random.Random(SCREAMING_SNAKE_CASE_)).to(SCREAMING_SNAKE_CASE_)
   lowercase__	: Any     		=   image.cpu().permute(0       ,	2       ,	3       ,	1)[0]
   lowercase__	: str     		=   Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_)).convert("""RGB""")
   if str(SCREAMING_SNAKE_CASE_).startswith("""mps"""):
     lowercase__	: Optional[int]     		=   torch.manual_seed(SCREAMING_SNAKE_CASE_)
   else:
     lowercase__	: List[Any]     		=   torch.Generator(device=SCREAMING_SNAKE_CASE_).manual_seed(SCREAMING_SNAKE_CASE_)
   lowercase__	: Union[str, Any]     		=   {
       """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       ,	SCREAMING_SNAKE_CASE_       ,	SCREAMING_SNAKE_CASE_=0):


   '''simple docstring'''




   lowercase__	: Tuple     		=   floats_tensor((1, 3, 32, 32)       ,	rng=random.Random(SCREAMING_SNAKE_CASE_)).to(SCREAMING_SNAKE_CASE_)
   lowercase__	: List[str]     		=   image.cpu().permute(0       ,	2       ,	3       ,	1)[0]
   lowercase__	: Union[str, Any]     		=   Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE_)).convert("""RGB""")
   if str(SCREAMING_SNAKE_CASE_).startswith("""mps"""):
     lowercase__	: List[str]     		=   torch.manual_seed(SCREAMING_SNAKE_CASE_)
   else:
     lowercase__	: Union[str, Any]     		=   torch.Generator(device=SCREAMING_SNAKE_CASE_).manual_seed(SCREAMING_SNAKE_CASE_)
   lowercase__	: List[Any]     		=   {
       """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):


   '''simple docstring'''




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

   lowercase__	: Any     		=   self.get_dummy_components()
   lowercase__	: Dict     		=   self.pipeline_class(**SCREAMING_SNAKE_CASE_)
   pipe.to(SCREAMING_SNAKE_CASE_)
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

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

   lowercase__	: Union[str, Any]     		=   self.get_dummy_inputs(SCREAMING_SNAKE_CASE_)
   lowercase__	: Union[str, Any]     		=   pipe(**SCREAMING_SNAKE_CASE_)[0]

   with tempfile.TemporaryDirectory() as tmpdir:
     pipe.save_pretrained(SCREAMING_SNAKE_CASE_)
     lowercase__	: str     		=   self.pipeline_class.from_pretrained(SCREAMING_SNAKE_CASE_)
     pipe_loaded.to(SCREAMING_SNAKE_CASE_)
     pipe_loaded.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

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

   lowercase__	: Optional[int]     		=   self.get_dummy_inputs(SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   pipe_loaded(**SCREAMING_SNAKE_CASE_)[0]

   lowercase__	: Tuple     		=   np.abs(output - output_loaded).max()
   self.assertLess(SCREAMING_SNAKE_CASE_       ,	1E-4)


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: str     		=   """cpu"""

   lowercase__	: Optional[Any]     		=   self.get_dummy_components()
   lowercase__	: Dict     		=   self.pipeline_class(**SCREAMING_SNAKE_CASE_)
   pipe.to(SCREAMING_SNAKE_CASE_)
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

   lowercase__	: Dict     		=   self.get_dummy_mask_inputs(SCREAMING_SNAKE_CASE_)
   lowercase__	: Optional[Any]     		=   pipe.generate_mask(**SCREAMING_SNAKE_CASE_)
   lowercase__	: str     		=   mask[0, -3:, -3:]

   self.assertEqual(mask.shape       ,	(1, 16, 16))
   lowercase__	: Optional[int]     		=   np.array([0] * 9)
   lowercase__	: Union[str, Any]     		=   np.abs(mask_slice.flatten() - expected_slice).max()
   self.assertLessEqual(SCREAMING_SNAKE_CASE_       ,	1E-3)
   self.assertEqual(mask[0, -3, -4]       ,	0)


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Any     		=   """cpu"""

   lowercase__	: List[Any]     		=   self.get_dummy_components()
   lowercase__	: Any     		=   self.pipeline_class(**SCREAMING_SNAKE_CASE_)
   pipe.to(SCREAMING_SNAKE_CASE_)
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

   lowercase__	: Union[str, Any]     		=   self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_)
   lowercase__	: Dict     		=   pipe.invert(**SCREAMING_SNAKE_CASE_).images
   lowercase__	: Optional[int]     		=   image[0, -1, -3:, -3:]

   self.assertEqual(image.shape       ,	(2, 32, 32, 3))
   lowercase__	: Any     		=   np.array(
       [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]       ,	)
   lowercase__	: Dict     		=   np.abs(image_slice.flatten() - expected_slice).max()
   self.assertLessEqual(SCREAMING_SNAKE_CASE_       ,	1E-3)


 def   lowercase__  (       self):


   '''simple docstring'''




   super().test_inference_batch_single_identical(expected_max_diff=5E-3)



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: List[Any]     		=   """cpu"""

   lowercase__	: Dict     		=   self.get_dummy_components()

   lowercase__	: Dict     		=   {"""beta_start""": 0.0_0_0_8_5, """beta_end""": 0.0_1_2, """beta_schedule""": """scaled_linear"""}
   lowercase__	: List[str]     		=   DPMSolverMultistepScheduler(**SCREAMING_SNAKE_CASE_)
   lowercase__	: Union[str, Any]     		=   DPMSolverMultistepInverseScheduler(**SCREAMING_SNAKE_CASE_)

   lowercase__	: Optional[int]     		=   self.pipeline_class(**SCREAMING_SNAKE_CASE_)
   pipe.to(SCREAMING_SNAKE_CASE_)
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

   lowercase__	: int     		=   self.get_dummy_inversion_inputs(SCREAMING_SNAKE_CASE_)
   lowercase__	: List[Any]     		=   pipe.invert(**SCREAMING_SNAKE_CASE_).images
   lowercase__	: Optional[Any]     		=   image[0, -1, -3:, -3:]

   self.assertEqual(image.shape       ,	(2, 32, 32, 3))
   lowercase__	: List[str]     		=   np.array(
       [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]       ,	)
   lowercase__	: List[str]     		=   np.abs(image_slice.flatten() - expected_slice).max()
   self.assertLessEqual(SCREAMING_SNAKE_CASE_       ,	1E-3)



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


 def   lowercase__  (       self):


   '''simple docstring'''




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


 @classmethod
 def   lowercase__  (       cls):


   '''simple docstring'''




   lowercase__	: List[str]     		=   load_image(
       """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""")

   lowercase__	: Dict     		=   raw_image.convert("""RGB""").resize((7_68, 7_68))

   lowercase__	: Any     		=   raw_image


 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Optional[Any]     		=   torch.manual_seed(0)

   lowercase__	: Optional[int]     		=   StableDiffusionDiffEditPipeline.from_pretrained(
       """stabilityai/stable-diffusion-2-1"""       ,	safety_checker=SCREAMING_SNAKE_CASE_       ,	torch_dtype=torch.floataa)
   lowercase__	: Optional[int]     		=   DDIMScheduler.from_config(pipe.scheduler.config)
   lowercase__	: str     		=   DDIMInverseScheduler.from_config(pipe.scheduler.config)
   pipe.enable_model_cpu_offload()
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

   lowercase__	: Tuple     		=   """a bowl of fruit"""
   lowercase__	: str     		=   """a bowl of pears"""

   lowercase__	: str     		=   pipe.generate_mask(
       image=self.raw_image       ,	source_prompt=SCREAMING_SNAKE_CASE_       ,	target_prompt=SCREAMING_SNAKE_CASE_       ,	generator=SCREAMING_SNAKE_CASE_       ,	)

   lowercase__	: Union[str, Any]     		=   pipe.invert(
       prompt=SCREAMING_SNAKE_CASE_       ,	image=self.raw_image       ,	inpaint_strength=0.7       ,	generator=SCREAMING_SNAKE_CASE_).latents

   lowercase__	: List[Any]     		=   pipe(
       prompt=SCREAMING_SNAKE_CASE_       ,	mask_image=SCREAMING_SNAKE_CASE_       ,	image_latents=SCREAMING_SNAKE_CASE_       ,	generator=SCREAMING_SNAKE_CASE_       ,	negative_prompt=SCREAMING_SNAKE_CASE_       ,	inpaint_strength=0.7       ,	output_type="""numpy"""       ,	).images[0]

   lowercase__	: List[Any]     		=   (
       np.array(
           load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/diffedit/pears.png""").resize((7_68, 7_68)))
       / 2_55
   )
   assert np.abs((expected_image - image).max()) < 5E-1



 def   lowercase__  (       self):


   '''simple docstring'''




   lowercase__	: Union[str, Any]     		=   torch.manual_seed(0)

   lowercase__	: Optional[Any]     		=   StableDiffusionDiffEditPipeline.from_pretrained(
       """stabilityai/stable-diffusion-2-1"""       ,	safety_checker=SCREAMING_SNAKE_CASE_       ,	torch_dtype=torch.floataa)
   lowercase__	: Any     		=   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
   lowercase__	: Union[str, Any]     		=   DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config)
   pipe.enable_model_cpu_offload()
   pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE_)

   lowercase__	: Tuple     		=   """a bowl of fruit"""
   lowercase__	: List[str]     		=   """a bowl of pears"""

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

   lowercase__	: List[Any]     		=   pipe.invert(
       prompt=SCREAMING_SNAKE_CASE_       ,	image=self.raw_image       ,	inpaint_strength=0.7       ,	generator=SCREAMING_SNAKE_CASE_       ,	num_inference_steps=25       ,	).latents

   lowercase__	: Union[str, Any]     		=   pipe(
       prompt=SCREAMING_SNAKE_CASE_       ,	mask_image=SCREAMING_SNAKE_CASE_       ,	image_latents=SCREAMING_SNAKE_CASE_       ,	generator=SCREAMING_SNAKE_CASE_       ,	negative_prompt=SCREAMING_SNAKE_CASE_       ,	inpaint_strength=0.7       ,	num_inference_steps=25       ,	output_type="""numpy"""       ,	).images[0]

   lowercase__	: Dict     		=   (
       np.array(
           load_image(
               """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
               """/diffedit/pears.png""").resize((7_68, 7_68)))
       / 2_55
   )
   assert np.abs((expected_image - image).max()) < 5E-1








# Copyright 2021 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.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


lowerCamelCase__     :		Any        = """Create a default config file for Accelerate with only a few flags set."""

def 		UpperCamelCase						(   lowercase_="no"			,			lowercase_ = default_json_config_file			,			lowercase_ = False )		->						Any:


  '''simple docstring'''






  lowercase__	: Any     		=   Path(lowercase_ )
  path.parent.mkdir(parents=lowercase_			,			exist_ok=lowercase_ )
  if path.exists():
    print(
        F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.' )
    return False
  lowercase__	: int     		=   mixed_precision.lower()
  if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
    raise ValueError(
        F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}' )
  lowercase__	: Dict     		=   {
      """compute_environment""": """LOCAL_MACHINE""",
      """mixed_precision""": mixed_precision,
  }
  if torch.cuda.is_available():
    lowercase__	: Any     		=   torch.cuda.device_count()
    lowercase__	: Any     		=   num_gpus
    lowercase__	: Optional[int]     		=   False
    if num_gpus > 1:
      lowercase__	: Tuple     		=   """MULTI_GPU"""
    else:
      lowercase__	: Optional[Any]     		=   """NO"""
  elif is_xpu_available() and use_xpu:
    lowercase__	: Union[str, Any]     		=   torch.xpu.device_count()
    lowercase__	: str     		=   num_xpus
    lowercase__	: List[Any]     		=   False
    if num_xpus > 1:
      lowercase__	: str     		=   """MULTI_XPU"""
    else:
      lowercase__	: Optional[Any]     		=   """NO"""
  elif is_npu_available():
    lowercase__	: Tuple     		=   torch.npu.device_count()
    lowercase__	: Union[str, Any]     		=   num_npus
    lowercase__	: Union[str, Any]     		=   False
    if num_npus > 1:
      lowercase__	: List[Any]     		=   """MULTI_NPU"""
    else:
      lowercase__	: int     		=   """NO"""
  else:
    lowercase__	: Union[str, Any]     		=   0
    lowercase__	: str     		=   True
    lowercase__	: Union[str, Any]     		=   1
    lowercase__	: int     		=   """NO"""
  lowercase__	: Tuple     		=   ClusterConfig(**lowercase_ )
  config.to_json_file(lowercase_ )
  return path

def 		UpperCamelCase						(   lowercase_			,			lowercase_ )		->						Optional[Any]:


  '''simple docstring'''






  lowercase__	: List[str]     		=   parser.add_parser("""default"""			,			parents=lowercase_			,			help=lowercase_			,			formatter_class=lowercase_ )
  parser.add_argument(
      """--config_file"""			,			default=lowercase_			,			help=(
          """The path to use to store the config file. Will default to a file named default_config.yaml in the cache """
          """location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have """
          """such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed """
          """with 'huggingface'."""
      )			,			dest="""save_location"""			,			)

  parser.add_argument(
      """--mixed_precision"""			,			choices=["""no""", """fp16""", """bf16"""]			,			type=lowercase_			,			help="""Whether or not to use mixed precision training. """
      """Choose between FP16 and BF16 (bfloat16) training. """
      """BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later."""			,			default="""no"""			,			)
  parser.set_defaults(func=lowercase_ )
  return parser



def 		UpperCamelCase						(   lowercase_ )		->						Any:


  '''simple docstring'''






  lowercase__	: Optional[Any]     		=   write_basic_config(args.mixed_precision			,			args.save_location )
  if config_file:
    print(F'accelerate configuration saved at {config_file}' )






