



'''simple docstring'''






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

      a						: 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			:  str						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  Optional[Any]=0     ):
      a						: Dict					       =					floats_tensor((1, 16, 16)						,      rng=random.Random(_SCREAMING_SNAKE_CASE     )     ).to(_SCREAMING_SNAKE_CASE     )
      a						: 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'     ):
        a						: Tuple					       =					torch.manual_seed(_SCREAMING_SNAKE_CASE     )
      else:
        a						: Optional[Any]					       =					torch.Generator(device=_SCREAMING_SNAKE_CASE     ).manual_seed(_SCREAMING_SNAKE_CASE     )
      a						: Union[str, 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			:  List[Any]						,      __snake_case			:  Union[str, Any]						,      __snake_case			:  int=0     ):
      a						: List[Any]					       =					floats_tensor((1, 3, 32, 32)						,      rng=random.Random(_SCREAMING_SNAKE_CASE     )     ).to(_SCREAMING_SNAKE_CASE     )
      a						: List[str]					       =					image.cpu().permute(0						,      2						,      3						,      1     )[0]
      a						: Any					       =					Image.fromarray(np.uinta(_SCREAMING_SNAKE_CASE     )     ).convert('RGB'     )
      if str(_SCREAMING_SNAKE_CASE     ).startswith('mps'     ):
        a						: Union[str, Any]					       =					torch.manual_seed(_SCREAMING_SNAKE_CASE     )
      else:
        a						: Optional[int]					       =					torch.Generator(device=_SCREAMING_SNAKE_CASE     ).manual_seed(_SCREAMING_SNAKE_CASE     )
      a						: List[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			:  Dict						,      __snake_case			:  List[str]						,      __snake_case			:  Dict=0     ):
      a						: Optional[Any]					       =					floats_tensor((1, 3, 32, 32)						,      rng=random.Random(_SCREAMING_SNAKE_CASE     )     ).to(_SCREAMING_SNAKE_CASE     )
      a						: Tuple					       =					image.cpu().permute(0						,      2						,      3						,      1     )[0]
      a						: int					       =					Image.fromarray(np.uinta(_SCREAMING_SNAKE_CASE     )     ).convert('RGB'     )
      if str(_SCREAMING_SNAKE_CASE     ).startswith('mps'     ):
        a						: Any					       =					torch.manual_seed(_SCREAMING_SNAKE_CASE     )
      else:
        a						: Optional[Any]					       =					torch.Generator(device=_SCREAMING_SNAKE_CASE     ).manual_seed(_SCREAMING_SNAKE_CASE     )
      a						: Tuple					       =					{
          '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			:  Optional[Any]     ):
      if not hasattr(self.pipeline_class						,      '_optional_components'     ):
        return

      a						: Tuple					       =					self.get_dummy_components()
      a						: Optional[Any]					       =					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}     )

      a						: Dict					       =					self.get_dummy_inputs(_SCREAMING_SNAKE_CASE     )
      a						: str					       =					pipe(**_SCREAMING_SNAKE_CASE     )[0]

      with tempfile.TemporaryDirectory() as tmpdir:
        pipe.save_pretrained(_SCREAMING_SNAKE_CASE     )
        a						: Optional[int]					       =					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."""						,      )

      a						: int					       =					self.get_dummy_inputs(_SCREAMING_SNAKE_CASE     )
      a						: str					       =					pipe_loaded(**_SCREAMING_SNAKE_CASE     )[0]

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







    def       lowercase_	(				self			:  int     ):
      a						: Any					       =					'cpu'

      a						: Tuple					       =					self.get_dummy_components()
      a						: List[Any]					       =					self.pipeline_class(**_SCREAMING_SNAKE_CASE     )
      pipe.to(_SCREAMING_SNAKE_CASE     )
      pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE     )

      a						: Any					       =					self.get_dummy_mask_inputs(_SCREAMING_SNAKE_CASE     )
      a						: Optional[Any]					       =					pipe.generate_mask(**_SCREAMING_SNAKE_CASE     )
      a						: Tuple					       =					mask[0, -3:, -3:]

      self.assertEqual(mask.shape						,      (1, 16, 16)     )
      a						: str					       =					np.array([0] * 9     )
      a						: Tuple					       =					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			:  Optional[int]     ):
      a						: Union[str, Any]					       =					'cpu'

      a						: Optional[Any]					       =					self.get_dummy_components()
      a						: Optional[int]					       =					self.pipeline_class(**_SCREAMING_SNAKE_CASE     )
      pipe.to(_SCREAMING_SNAKE_CASE     )
      pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE     )

      a						: Dict					       =					self.get_dummy_inversion_inputs(_SCREAMING_SNAKE_CASE     )
      a						: str					       =					pipe.invert(**_SCREAMING_SNAKE_CASE     ).images
      a						: Tuple					       =					image[0, -1, -3:, -3:]

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







    def       lowercase_	(				self			:  int     ):
      super().test_inference_batch_single_identical(expected_max_diff=5e-3     )







    def       lowercase_	(				self			:  Union[str, Any]     ):
      a						: List[Any]					       =					'cpu'

      a						: Optional[int]					       =					self.get_dummy_components()

      a						: Union[str, Any]					       =					{'beta_start': 0.00085, 'beta_end': 0.012, 'beta_schedule': 'scaled_linear'}
      a						: Any					       =					DPMSolverMultistepScheduler(**_SCREAMING_SNAKE_CASE     )
      a						: Optional[int]					       =					DPMSolverMultistepInverseScheduler(**_SCREAMING_SNAKE_CASE     )

      a						: str					       =					self.pipeline_class(**_SCREAMING_SNAKE_CASE     )
      pipe.to(_SCREAMING_SNAKE_CASE     )
      pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE     )

      a						: Any					       =					self.get_dummy_inversion_inputs(_SCREAMING_SNAKE_CASE     )
      a						: Tuple					       =					pipe.invert(**_SCREAMING_SNAKE_CASE     ).images
      a						: Optional[int]					       =					image[0, -1, -3:, -3:]

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

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







    def       lowercase_	(				self			:  Dict     ):
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()







    @classmethod
    def       lowercase_	(				cls			:  Union[str, Any]     ):
      a						: Tuple					       =					load_image(
          'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png'     )

      a						: Tuple					       =					raw_image.convert('RGB'     ).resize((7_68, 7_68)     )

      a						: Union[str, Any]					       =					raw_image







    def       lowercase_	(				self			:  List[Any]     ):
      a						: Tuple					       =					torch.manual_seed(0     )

      a						: int					       =					StableDiffusionDiffEditPipeline.from_pretrained(
          'stabilityai/stable-diffusion-2-1'						,      safety_checker=_SCREAMING_SNAKE_CASE						,      torch_dtype=torch.floataa     )
      a						: Union[str, Any]					       =					DDIMScheduler.from_config(pipe.scheduler.config     )
      a						: Tuple					       =					DDIMInverseScheduler.from_config(pipe.scheduler.config     )
      pipe.enable_model_cpu_offload()
      pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE     )

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

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

      a						: int					       =					pipe.invert(
          prompt=_SCREAMING_SNAKE_CASE						,      image=self.raw_image						,      inpaint_strength=0.7						,      generator=_SCREAMING_SNAKE_CASE     ).latents

      a						: Optional[int]					       =					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]

      a						: str					       =					(
          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			:  Optional[Any]     ):
      a						: int					       =					torch.manual_seed(0     )

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

      a						: int					       =					'a bowl of fruit'
      a						: Dict					       =					'a bowl of pears'

      a						: Tuple					       =					pipe.generate_mask(
          image=self.raw_image						,      source_prompt=_SCREAMING_SNAKE_CASE						,      target_prompt=_SCREAMING_SNAKE_CASE						,      generator=_SCREAMING_SNAKE_CASE						,      )

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

      a						: Optional[int]					       =					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]

      a						: 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







'''simple docstring'''






import math

class 							a__:







    def __init__(				self			:  int						,      __snake_case			:  Any=0     ):  # a graph with Node 0,1,...,N-1
      a						: List[Any]					       =					n
      a						: Optional[Any]					       =					[
          [math.inf for j in range(0						,      __snake_case     )] for i in range(0						,      __snake_case     )
      ]  # adjacency matrix for weight
      a						: Dict					       =					[
          [math.inf for j in range(0						,      __snake_case     )] for i in range(0						,      __snake_case     )
      ]  # dp[i][j] stores minimum distance from i to j







    def       lowercase_	(				self			:  int						,      __snake_case			:  str						,      __snake_case			:  Tuple						,      __snake_case			:  int     ):
      a						: str					       =					w







    def       lowercase_	(				self			:  int     ):
      for k in range(0						,      self.n     ):
        for i in range(0						,      self.n     ):
          for j in range(0						,      self.n     ):
            a						: str					       =					min(self.dp[i][j]						,      self.dp[i][k] + self.dp[k][j]     )







    def       lowercase_	(				self			:  List[str]						,      __snake_case			:  Any						,      __snake_case			:  List[str]     ):
      return self.dp[u][v]


if __name__ == "__main__":
     lowerCAmelCase: Any							=						Graph(5)
     graph.add_edge(0, 2, 9)
     graph.add_edge(0, 4, 1_0)
     graph.add_edge(1, 3, 5)
     graph.add_edge(2, 3, 7)
     graph.add_edge(3, 0, 1_0)
     graph.add_edge(3, 1, 2)
     graph.add_edge(3, 2, 1)
     graph.add_edge(3, 4, 6)
     graph.add_edge(4, 1, 3)
     graph.add_edge(4, 2, 4)
     graph.add_edge(4, 3, 9)
     graph.floyd_warshall()
     graph.show_min(1, 4)
     graph.show_min(0, 3)