
import gc
import random
import tempfile
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.semantic_stable_diffusion import SemanticStableDiffusionPipeline as StableDiffusionPipeline
from diffusers.utils import floats_tensor, nightly, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()

class        UpperCamelCase__(    unittest.TestCase	):

	"""simple docstring"""

	def        _a					(      self				:			Optional[int] ):
			"""simple docstring"""





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







	@property
	def        _a					(      self				:			Tuple ):
			"""simple docstring"""





			A				=1
			A				=3
			A				=(32, 32)

			A				=floats_tensor((batch_size, num_channels) + sizes							,			rng=random.Random(0 ) ).to(snake_case__ )
			return image







	@property
	def        _a					(      self				:			Optional[int] ):
			"""simple docstring"""





			torch.manual_seed(0 )
			A				=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							,			)
			return model







	@property
	def        _a					(      self				:			Union[str, Any] ):
			"""simple docstring"""





			torch.manual_seed(0 )
			A				=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							,			)
			return model







	@property
	def        _a					(      self				:			str ):
			"""simple docstring"""





			torch.manual_seed(0 )
			A				=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							,			)
			return CLIPTextModel(snake_case__ )







	@property
	def        _a					(      self				:			Any ):
			"""simple docstring"""





			def extract(*snake_case__				:			Union[str, Any]							,			**snake_case__				:			str ):

					class        UpperCamelCase__:

						"""simple docstring"""

						def __init__(      self				:			Optional[Any] ):
								"""simple docstring"""





								A				=torch.ones([0] )







						def        _a					(      self				:			List[Any]							,			snake_case__				:			List[Any] ):
								"""simple docstring"""





								self.pixel_values.to(snake_case__ )
								return self


					return Out()

			return extract







	def        _a					(      self				:			List[Any] ):
			"""simple docstring"""





			A				="cpu"  # ensure determinism for the device-dependent torch.Generator
			A				=self.dummy_cond_unet
			A				=DDIMScheduler(
			    beta_start=0.00_085							,			beta_end=0.012							,			beta_schedule="scaled_linear"							,			clip_sample=snake_case__							,			set_alpha_to_one=snake_case__							,			)

			A				=self.dummy_vae
			A				=self.dummy_text_encoder
			A				=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

			# make sure here that pndm scheduler skips prk
			A				=StableDiffusionPipeline(
			    unet=snake_case__							,			scheduler=snake_case__							,			vae=snake_case__							,			text_encoder=snake_case__							,			tokenizer=snake_case__							,			safety_checker=snake_case__							,			feature_extractor=self.dummy_extractor							,			)
			A				=sd_pipe.to(snake_case__ )
			sd_pipe.set_progress_bar_config(disable=snake_case__ )

			A				="A painting of a squirrel eating a burger"

			A				=torch.Generator(device=snake_case__ ).manual_seed(0 )
			A				=sd_pipe([prompt]							,			generator=snake_case__							,			guidance_scale=6.0							,			num_inference_steps=2							,			output_type="np" )
			A				=output.images

			A				=torch.Generator(device=snake_case__ ).manual_seed(0 )
			A				=sd_pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=6.0							,			num_inference_steps=2							,			output_type="np"							,			return_dict=snake_case__							,			)[0]

			A				=image[0, -3:, -3:, -1]
			A				=image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)
			A				=np.array([0.5_753, 0.6_114, 0.5_001, 0.5_034, 0.5_470, 0.4_729, 0.4_971, 0.4_867, 0.4_867] )

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







	def        _a					(      self				:			str ):
			"""simple docstring"""





			A				="cpu"  # ensure determinism for the device-dependent torch.Generator
			A				=self.dummy_cond_unet
			A				=PNDMScheduler(skip_prk_steps=snake_case__ )
			A				=self.dummy_vae
			A				=self.dummy_text_encoder
			A				=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

			# make sure here that pndm scheduler skips prk
			A				=StableDiffusionPipeline(
			    unet=snake_case__							,			scheduler=snake_case__							,			vae=snake_case__							,			text_encoder=snake_case__							,			tokenizer=snake_case__							,			safety_checker=snake_case__							,			feature_extractor=self.dummy_extractor							,			)
			A				=sd_pipe.to(snake_case__ )
			sd_pipe.set_progress_bar_config(disable=snake_case__ )

			A				="A painting of a squirrel eating a burger"
			A				=torch.Generator(device=snake_case__ ).manual_seed(0 )
			A				=sd_pipe([prompt]							,			generator=snake_case__							,			guidance_scale=6.0							,			num_inference_steps=2							,			output_type="np" )

			A				=output.images

			A				=torch.Generator(device=snake_case__ ).manual_seed(0 )
			A				=sd_pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=6.0							,			num_inference_steps=2							,			output_type="np"							,			return_dict=snake_case__							,			)[0]

			A				=image[0, -3:, -3:, -1]
			A				=image_from_tuple[0, -3:, -3:, -1]

			assert image.shape == (1, 64, 64, 3)
			A				=np.array([0.5_122, 0.5_712, 0.4_825, 0.5_053, 0.5_646, 0.4_769, 0.5_179, 0.4_894, 0.4_994] )

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







	def        _a					(      self				:			Tuple ):
			"""simple docstring"""





			A				=StableDiffusionPipeline.from_pretrained(
			    "hf-internal-testing/tiny-stable-diffusion-lms-pipe"							,			safety_checker=snake_case__ )
			assert isinstance(snake_case__							,			snake_case__ )
			assert isinstance(pipe.scheduler							,			snake_case__ )
			assert pipe.safety_checker is None

			A				=pipe("example prompt"							,			num_inference_steps=2 ).images[0]
			assert image is not None

			# check that there's no error when saving a pipeline with one of the models being None
			with tempfile.TemporaryDirectory() as tmpdirname:
					pipe.save_pretrained(snake_case__ )
					A				=StableDiffusionPipeline.from_pretrained(snake_case__ )

			# sanity check that the pipeline still works
			assert pipe.safety_checker is None
			A				=pipe("example prompt"							,			num_inference_steps=2 ).images[0]
			assert image is not None







	@unittest.skipIf(torch_device != "cuda"							,			"This test requires a GPU" )
	def        _a					(      self				:			Union[str, Any] ):
			"""simple docstring"""





			A				=self.dummy_cond_unet
			A				=PNDMScheduler(skip_prk_steps=snake_case__ )
			A				=self.dummy_vae
			A				=self.dummy_text_encoder
			A				=CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

			# put models in fp16
			A				=unet.half()
			A				=vae.half()
			A				=bert.half()

			# make sure here that pndm scheduler skips prk
			A				=StableDiffusionPipeline(
			    unet=snake_case__							,			scheduler=snake_case__							,			vae=snake_case__							,			text_encoder=snake_case__							,			tokenizer=snake_case__							,			safety_checker=snake_case__							,			feature_extractor=self.dummy_extractor							,			)
			A				=sd_pipe.to(snake_case__ )
			sd_pipe.set_progress_bar_config(disable=snake_case__ )

			A				="A painting of a squirrel eating a burger"
			A				=sd_pipe([prompt]							,			num_inference_steps=2							,			output_type="np" ).images

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


@nightly
@require_torch_gpu
class        UpperCamelCase__(    unittest.TestCase	):

	"""simple docstring"""

	def        _a					(      self				:			Dict ):
			"""simple docstring"""





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







	def        _a					(      self				:			Union[str, Any] ):
			"""simple docstring"""





			A				="cuda"
			A				=StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" )
			A				=pipe.to(snake_case__ )
			pipe.set_progress_bar_config(disable=snake_case__ )

			A				="a photo of a cat"
			A				={
			    "editing_prompt": ["sunglasses"],
			    "reverse_editing_direction": [False],
			    "edit_warmup_steps": 10,
			    "edit_guidance_scale": 6,
			    "edit_threshold": 0.95,
			    "edit_momentum_scale": 0.5,
			    "edit_mom_beta": 0.6,
			}

			A				=3
			A				=7

			# no sega enabled
			A				=torch.Generator(snake_case__ )
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.34_673_113,
			    0.38_492_733,
			    0.37_597_352,
			    0.34_086_335,
			    0.35_650_748,
			    0.35_579_205,
			    0.3_384_763,
			    0.34_340_236,
			    0.3_573_271,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			# with sega enabled
			# generator = torch.manual_seed(seed)
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			**snake_case__							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.41_887_826,
			    0.37_728_766,
			    0.30_138_272,
			    0.41_416_335,
			    0.41_664_985,
			    0.36_283_392,
			    0.36_191_246,
			    0.43_364_465,
			    0.43_001_732,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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







	def        _a					(      self				:			List[Any] ):
			"""simple docstring"""





			A				="cuda"
			A				=StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" )
			A				=pipe.to(snake_case__ )
			pipe.set_progress_bar_config(disable=snake_case__ )

			A				="an image of a crowded boulevard, realistic, 4k"
			A				={
			    "editing_prompt": "crowd, crowded, people",
			    "reverse_editing_direction": True,
			    "edit_warmup_steps": 10,
			    "edit_guidance_scale": 8.3,
			    "edit_threshold": 0.9,
			    "edit_momentum_scale": 0.5,
			    "edit_mom_beta": 0.6,
			}

			A				=9
			A				=7

			# no sega enabled
			A				=torch.Generator(snake_case__ )
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.43_497_998,
			    0.91_814_065,
			    0.7_540_739,
			    0.55_580_205,
			    0.8_467_265,
			    0.5_389_691,
			    0.62_574_506,
			    0.58_897_763,
			    0.50_926_757,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			# with sega enabled
			# generator = torch.manual_seed(seed)
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			**snake_case__							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.3_089_719,
			    0.30_500_144,
			    0.29_016_042,
			    0.30_630_964,
			    0.325_687,
			    0.29_419_225,
			    0.2_908_091,
			    0.28_723_598,
			    0.27_696_294,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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







	def        _a					(      self				:			Optional[Any] ):
			"""simple docstring"""





			A				="cuda"
			A				=StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5" )
			A				=pipe.to(snake_case__ )
			pipe.set_progress_bar_config(disable=snake_case__ )

			A				="a castle next to a river"
			A				={
			    "editing_prompt": ["boat on a river, boat", "monet, impression, sunrise"],
			    "reverse_editing_direction": False,
			    "edit_warmup_steps": [15, 18],
			    "edit_guidance_scale": 6,
			    "edit_threshold": [0.9, 0.8],
			    "edit_momentum_scale": 0.5,
			    "edit_mom_beta": 0.6,
			}

			A				=48
			A				=7

			# no sega enabled
			A				=torch.Generator(snake_case__ )
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.75_163_555,
			    0.76_037_145,
			    0.61_785,
			    0.9_189_673,
			    0.8_627_701,
			    0.85_189_694,
			    0.8_512_813,
			    0.87_012_076,
			    0.8_312_857,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			# with sega enabled
			# generator = torch.manual_seed(seed)
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			**snake_case__							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.73_553_365,
			    0.7_537_271,
			    0.74_341_905,
			    0.66_480_356,
			    0.6_472_925,
			    0.63_039_416,
			    0.64_812_905,
			    0.6_749_717,
			    0.6_517_102,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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







	def        _a					(      self				:			Optional[Any] ):
			"""simple docstring"""





			A				="cuda"
			A				=StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5"							,			torch_dtype=torch.floataa )
			A				=pipe.to(snake_case__ )
			pipe.set_progress_bar_config(disable=snake_case__ )

			A				="a photo of a cat"
			A				={
			    "editing_prompt": ["sunglasses"],
			    "reverse_editing_direction": [False],
			    "edit_warmup_steps": 10,
			    "edit_guidance_scale": 6,
			    "edit_threshold": 0.95,
			    "edit_momentum_scale": 0.5,
			    "edit_mom_beta": 0.6,
			}

			A				=3
			A				=7

			# no sega enabled
			A				=torch.Generator(snake_case__ )
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.34_887_695,
			    0.3_876_953,
			    0.375,
			    0.34_423_828,
			    0.3_581_543,
			    0.35_717_773,
			    0.3_383_789,
			    0.34_570_312,
			    0.359_375,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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

			# with sega enabled
			# generator = torch.manual_seed(seed)
			generator.manual_seed(snake_case__ )
			A				=pipe(
			    [prompt]							,			generator=snake_case__							,			guidance_scale=snake_case__							,			num_inference_steps=50							,			output_type="np"							,			width=5_12							,			height=5_12							,			**snake_case__							,			)

			A				=output.images
			A				=image[0, -3:, -3:, -1]
			A				=[
			    0.42_285_156,
			    0.36_914_062,
			    0.29_077_148,
			    0.42_041_016,
			    0.41_918_945,
			    0.35_498_047,
			    0.3_618_164,
			    0.4_423_828,
			    0.43_115_234,
			]

			assert image.shape == (1, 5_12, 5_12, 3)

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






from __future__ import annotations

from typing import Any

class        UpperCamelCase__:

	"""simple docstring"""

	def __init__(      self				:			Dict							,			snake_case__				:			Any							,			snake_case__				:			Any ):  # noqa: A002
			"""simple docstring"""





			A				=item
			A				=next


class        UpperCamelCase__:

	"""simple docstring"""

	def __init__(      self				:			Optional[Any] ):
			"""simple docstring"""





			A				=None
			A				=0







	def        _a					(      self				:			str							,			snake_case__				:			Any ):
			"""simple docstring"""





			A				=Node(snake_case__							,			self.head )
			self.size += 1







	def        _a					(      self				:			Dict ):
			"""simple docstring"""





			if self.head is None:
					return None
			else:
					A				=self.head.item
					A				=self.head.next
					self.size -= 1
					return item







	def        _a					(      self				:			Any ):
			"""simple docstring"""





			return self.head is None







	def __str__(      self				:			Dict ):
			"""simple docstring"""





			if self.is_empty():
					return ""
			else:
					A				=self.head
					A				=""
					A				=[]
					while iterate:
							item_list.append(str(iterate.item ) )
							A				=iterate.next

					A				=" --> ".join(snake_case__ )

					return item_str







	def __len__(      self				:			Union[str, Any] ):
			"""simple docstring"""





			return self.size




