


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




					def  snake_case__  (					self):
								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""")							,							cross_attention_dim=32							,							attention_head_dim=(2, 4)							,							use_linear_projection=__SCREAMING_SNAKE_CASE							,							)
								UpperCAmelCase__     :    Dict         =   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							,							)
								UpperCAmelCase__     :    Tuple         =   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)
								UpperCAmelCase__     :    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=128							,							)
								torch.manual_seed(0)
								UpperCAmelCase__     :    List[str]         =   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							,							)
								UpperCAmelCase__     :    Optional[Any]         =   CLIPTextModel(__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    Any         =   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

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

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

								UpperCAmelCase__     :    Optional[int]         =   self.get_dummy_components()
								UpperCAmelCase__     :    Union[str, 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})

								UpperCAmelCase__     :    Tuple         =   self.get_dummy_inputs(__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    str         =   pipe(**__SCREAMING_SNAKE_CASE)[0]

								with tempfile.TemporaryDirectory() as tmpdir:
											pipe.save_pretrained(__SCREAMING_SNAKE_CASE)
											UpperCAmelCase__     :    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.'''							,							)

								UpperCAmelCase__     :    Union[str, Any]         =   self.get_dummy_inputs(__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    Optional[Any]         =   pipe_loaded(**__SCREAMING_SNAKE_CASE)[0]

								UpperCAmelCase__     :    List[str]         =   np.abs(output - output_loaded).max()
								self.assertLess(__SCREAMING_SNAKE_CASE							,							1e-4)




					def  snake_case__  (					self):
								UpperCAmelCase__     :    Tuple         =   """cpu"""

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

								UpperCAmelCase__     :    List[Any]         =   self.get_dummy_mask_inputs(__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    List[str]         =   pipe.generate_mask(**__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    Optional[Any]         =   mask[0, -3:, -3:]

								self.assertEqual(mask.shape							,							(1, 16, 16))
								UpperCAmelCase__     :    List[Any]         =   np.array([0] * 9)
								UpperCAmelCase__     :    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  snake_case__  (					self):
								UpperCAmelCase__     :    Union[str, Any]         =   """cpu"""

								UpperCAmelCase__     :    Union[str, Any]         =   self.get_dummy_components()
								UpperCAmelCase__     :    int         =   self.pipeline_class(**__SCREAMING_SNAKE_CASE)
								pipe.to(__SCREAMING_SNAKE_CASE)
								pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE)

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

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




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




					def  snake_case__  (					self):
								UpperCAmelCase__     :    Optional[Any]         =   """cpu"""

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

								UpperCAmelCase__     :    List[str]         =   {"""beta_start""": 0.00085, """beta_end""": 0.012, """beta_schedule""": """scaled_linear"""}
								UpperCAmelCase__     :    Optional[Any]         =   DPMSolverMultistepScheduler(**__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    Any         =   DPMSolverMultistepInverseScheduler(**__SCREAMING_SNAKE_CASE)

								UpperCAmelCase__     :    List[str]         =   self.pipeline_class(**__SCREAMING_SNAKE_CASE)
								pipe.to(__SCREAMING_SNAKE_CASE)
								pipe.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE)

								UpperCAmelCase__     :    Any         =   self.get_dummy_inversion_inputs(__SCREAMING_SNAKE_CASE)
								UpperCAmelCase__     :    Tuple         =   pipe.invert(**__SCREAMING_SNAKE_CASE).images
								UpperCAmelCase__     :    Union[str, Any]         =   image[0, -1, -3:, -3:]

								self.assertEqual(image.shape							,							(2, 32, 32, 3))
								UpperCAmelCase__     :    Optional[int]         =   np.array(
								    [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]							,							)
								UpperCAmelCase__     :    Optional[int]         =   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  snake_case__  (					self):
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()




					@classmethod
					def  snake_case__  (					cls):
								UpperCAmelCase__     :    Optional[Any]         =   load_image(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png""")

								UpperCAmelCase__     :    Dict         =   raw_image.convert("""RGB""").resize((768, 768))

								UpperCAmelCase__     :    str         =   raw_image




					def  snake_case__  (					self):
								UpperCAmelCase__     :    str         =   torch.manual_seed(0)

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

								UpperCAmelCase__     :    Dict         =   """a bowl of fruit"""
								UpperCAmelCase__     :    str         =   """a bowl of pears"""

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

								UpperCAmelCase__     :    List[Any]         =   pipe.invert(
								    prompt=__SCREAMING_SNAKE_CASE							,							image=self.raw_image							,							inpaint_strength=0.7							,							generator=__SCREAMING_SNAKE_CASE).latents

								UpperCAmelCase__     :    Tuple         =   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]

								UpperCAmelCase__     :    List[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




					def  snake_case__  (					self):
								UpperCAmelCase__     :    Optional[Any]         =   torch.manual_seed(0)

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

								UpperCAmelCase__     :    List[Any]         =   """a bowl of fruit"""
								UpperCAmelCase__     :    Any         =   """a bowl of pears"""

								UpperCAmelCase__     :    str         =   pipe.generate_mask(
								    image=self.raw_image							,							source_prompt=__SCREAMING_SNAKE_CASE							,							target_prompt=__SCREAMING_SNAKE_CASE							,							generator=__SCREAMING_SNAKE_CASE							,							)

								UpperCAmelCase__     :    Optional[Any]         =   pipe.invert(
								    prompt=__SCREAMING_SNAKE_CASE							,							image=self.raw_image							,							inpaint_strength=0.7							,							generator=__SCREAMING_SNAKE_CASE							,							num_inference_steps=25							,							).latents

								UpperCAmelCase__     :    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]

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




from __future__ import annotations

from typing import Any





def      __snake_case	(			_UpperCAmelCase				):
    if not postfix_notation:
        return 0

    __a						       =				{'''+''', '''-''', '''*''', '''/'''}
    __a						       =				[]

    for token in postfix_notation:
        if token in operations:
            __a       ,   __a						       =				stack.pop(), stack.pop()
            if token == "+":
                stack.append(a + b				)
            elif token == "-":
                stack.append(a - b				)
            elif token == "*":
                stack.append(a * b				)
            else:
                if a * b < 0 and a % b != 0:
                    stack.append(a // b + 1				)
                else:
                    stack.append(a // b				)
        else:
            stack.append(int(_UpperCAmelCase				)				)

    return stack.pop()


if __name__ == "__main__":
 import doctest

 doctest.testmod()





