



import gc
import random
import unittest

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

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()






class     __a			(  SCREAMING_SNAKE_CASE						,     SCREAMING_SNAKE_CASE						,     unittest.TestCase					):
	SCREAMING_SNAKE_CASE  	=							StableDiffusionXLImgaImgPipeline
	SCREAMING_SNAKE_CASE  	=							TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
	SCREAMING_SNAKE_CASE  	=							PipelineTesterMixin.required_optional_params - {"latents"}
	SCREAMING_SNAKE_CASE  	=							TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	SCREAMING_SNAKE_CASE  	=							IMAGE_TO_IMAGE_IMAGE_PARAMS
	SCREAMING_SNAKE_CASE  	=							IMAGE_TO_IMAGE_IMAGE_PARAMS



	def 		UpperCamelCase				(    self				:     Dict)->				Tuple:
						torch.manual_seed(0)
						__lowerCAmelCase						 =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""")					,						attention_head_dim=(2, 4)					,						use_linear_projection=snake_case_					,						addition_embed_type="""text_time"""					,						addition_time_embed_dim=8					,						transformer_layers_per_block=(1, 2)					,						projection_class_embeddings_input_dim=80					,						cross_attention_dim=64					,						)
						__lowerCAmelCase						 =EulerDiscreteScheduler(
						    beta_start=0.0_0_0_8_5					,						beta_end=0.0_1_2					,						steps_offset=1					,						beta_schedule="""scaled_linear"""					,						timestep_spacing="""leading"""					,						)
						torch.manual_seed(0)
						__lowerCAmelCase						 =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)
						__lowerCAmelCase						 =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=32					,						)
						__lowerCAmelCase						 =CLIPTextModel(snake_case_)
						__lowerCAmelCase						 =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					,						local_files_only=snake_case_)

						__lowerCAmelCase						 =CLIPTextModelWithProjection(snake_case_)
						__lowerCAmelCase						 =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""					,						local_files_only=snake_case_)

						__lowerCAmelCase						 ={
						    """unet""": unet,
						    """scheduler""": scheduler,
						    """vae""": vae,
						    """text_encoder""": text_encoder,
						    """tokenizer""": tokenizer,
						    """text_encoder_2""": text_encoder_a,
						    """tokenizer_2""": tokenizer_a,
						    # "safety_checker": None,
						    # "feature_extractor": None,
						}
						return components



	def 		UpperCamelCase				(    self				:     Optional[int]					,						snake_case_				:     Union[str, Any]					,						snake_case_				:     Tuple=0)->				int:
						__lowerCAmelCase						 =floats_tensor((1, 3, 32, 32)					,						rng=random.Random(snake_case_)).to(snake_case_)
						__lowerCAmelCase						 =image / 2 + 0.5
						if str(snake_case_).startswith("""mps"""):
											__lowerCAmelCase						 =torch.manual_seed(snake_case_)
						else:
											__lowerCAmelCase						 =torch.Generator(device=snake_case_).manual_seed(snake_case_)
						__lowerCAmelCase						 ={
						    """prompt""": """A painting of a squirrel eating a burger""",
						    """image""": image,
						    """generator""": generator,
						    """num_inference_steps""": 2,
						    """guidance_scale""": 5.0,
						    """output_type""": """numpy""",
						    """strength""": 0.7_5,
						}
						return inputs



	def 		UpperCamelCase				(    self				:     Optional[Any])->				Dict:
						__lowerCAmelCase						 ="""cpu"""  # ensure determinism for the device-dependent torch.Generator
						__lowerCAmelCase						 =self.get_dummy_components()
						__lowerCAmelCase						 =StableDiffusionXLImgaImgPipeline(**snake_case_)
						__lowerCAmelCase						 =sd_pipe.to(snake_case_)
						sd_pipe.set_progress_bar_config(disable=snake_case_)

						__lowerCAmelCase						 =self.get_dummy_inputs(snake_case_)
						__lowerCAmelCase						 =sd_pipe(**snake_case_).images
						__lowerCAmelCase						 =image[0, -3:, -3:, -1]

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

						__lowerCAmelCase						 =np.array([0.4_6_5_6, 0.4_8_4_0, 0.4_4_3_9, 0.6_6_9_8, 0.5_5_7_4, 0.4_5_2_4, 0.5_7_9_9, 0.5_9_4_3, 0.5_1_6_5])

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



	def 		UpperCamelCase				(    self				:     Optional[Any])->				Optional[Any]:
						super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)



	def 		UpperCamelCase				(    self				:     Union[str, Any])->				Tuple:
						super().test_inference_batch_single_identical(expected_max_diff=3e-3)



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



	def 		UpperCamelCase				(    self				:     List[Any])->				int:
						__lowerCAmelCase						 =self.get_dummy_components()
						__lowerCAmelCase						 =StableDiffusionXLImgaImgPipeline(**snake_case_)
						__lowerCAmelCase						 =sd_pipe.to(snake_case_)
						__lowerCAmelCase						 =sd_pipe.to(snake_case_)
						sd_pipe.set_progress_bar_config(disable=snake_case_)

						# forward without prompt embeds
						__lowerCAmelCase						 =self.get_dummy_inputs(snake_case_)
						__lowerCAmelCase						 =3 * ["""this is a negative prompt"""]
						__lowerCAmelCase						 =negative_prompt
						__lowerCAmelCase						 =3 * [inputs["""prompt"""]]

						__lowerCAmelCase						 =sd_pipe(**snake_case_)
						__lowerCAmelCase						 =output.images[0, -3:, -3:, -1]

						# forward with prompt embeds
						__lowerCAmelCase						 =self.get_dummy_inputs(snake_case_)
						__lowerCAmelCase						 =3 * ["""this is a negative prompt"""]
						__lowerCAmelCase						 =3 * [inputs.pop("""prompt""")]

						(
						    (
						    __lowerCAmelCase
						) ,						(
						    __lowerCAmelCase
						) ,						(
						    __lowerCAmelCase
						) ,						(
						    __lowerCAmelCase
						) ,						
						)						 =sd_pipe.encode_prompt(snake_case_					,						negative_prompt=snake_case_)

						__lowerCAmelCase						 =sd_pipe(
						    **snake_case_					,						prompt_embeds=snake_case_					,						negative_prompt_embeds=snake_case_					,						pooled_prompt_embeds=snake_case_					,						negative_pooled_prompt_embeds=snake_case_					,						)
						__lowerCAmelCase						 =output.images[0, -3:, -3:, -1]

						# make sure that it's equal
						assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1e-4






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



	def 		UpperCamelCase				(    self				:     str)->				Optional[Any]:
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()



	def 		UpperCamelCase				(    self				:     Optional[int]					,						snake_case_				:     List[Any]					,						snake_case_				:     Any="cpu"					,						snake_case_				:     Tuple=torch.floataa					,						snake_case_				:     Dict=0)->				Optional[Any]:
						__lowerCAmelCase						 =torch.Generator(device=snake_case_).manual_seed(snake_case_)
						__lowerCAmelCase						 =np.random.RandomState(snake_case_).standard_normal((1, 4, 64, 64))
						__lowerCAmelCase						 =torch.from_numpy(snake_case_).to(device=snake_case_					,						dtype=snake_case_)
						__lowerCAmelCase						 ={
						    """prompt""": """a photograph of an astronaut riding a horse""",
						    """latents""": latents,
						    """generator""": generator,
						    """num_inference_steps""": 3,
						    """guidance_scale""": 7.5,
						    """output_type""": """numpy""",
						}
						return inputs



	def 		UpperCamelCase				(    self				:     Dict)->				str:
						__lowerCAmelCase						 =DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base""")
						pipe.to(snake_case_)
						pipe.set_progress_bar_config(disable=snake_case_)

						__lowerCAmelCase						 =self.get_inputs(snake_case_)
						__lowerCAmelCase						 =pipe(**snake_case_).images
						__lowerCAmelCase						 =image[0, -3:, -3:, -1].flatten()

						assert image.shape == (1, 5_12, 5_12, 3)
						__lowerCAmelCase						 =np.array([0.4_9_4_9_3, 0.4_7_8_9_6, 0.4_0_7_9_8, 0.5_4_2_1_4, 0.5_3_2_1_2, 0.4_8_2_0_2, 0.4_7_6_5_6, 0.4_6_3_2_9, 0.4_8_5_0_6])
						assert np.abs(image_slice - expected_slice).max() < 7e-3









from __future__ import annotations

import math
from collections import Counter
from string import ascii_lowercase






def        __lowerCAmelCase		(	__lowerCamelCase						:     str						)	->    None:
					__lowerCAmelCase ,						__lowerCAmelCase						 =analyze_text(__lowerCamelCase						)
					__lowerCAmelCase						 =list(""" """ + ascii_lowercase						)
					# what is our total sum of probabilities.
					__lowerCAmelCase						 =sum(single_char_strings.values()						)

					# one length string
					__lowerCAmelCase						 =0
					# for each alpha we go in our dict and if it is in it we calculate entropy
					for ch in my_alphas:
										if ch in single_char_strings:
															__lowerCAmelCase						 =single_char_strings[ch]
															__lowerCAmelCase						 =my_str / all_sum
															my_fir_sum += prob * math.loga(__lowerCamelCase						)  # entropy formula.

    # print entropy
					print(f"""{round(-1 * my_fir_sum						):.1f}"""						)

					# two len string
					__lowerCAmelCase						 =sum(two_char_strings.values()						)
					__lowerCAmelCase						 =0
					# for each alpha (two in size) calculate entropy.
					for cha in my_alphas:
										for cha in my_alphas:
															__lowerCAmelCase						 =cha + cha
															if sequence in two_char_strings:
																				__lowerCAmelCase						 =two_char_strings[sequence]
																				__lowerCAmelCase						 =int(__lowerCamelCase						) / all_sum
																				my_sec_sum += prob * math.loga(__lowerCamelCase						)

    # print second entropy
					print(f"""{round(-1 * my_sec_sum						):.1f}"""						)

					# print the difference between them
					print(f"""{round((-1 * my_sec_sum) - (-1 * my_fir_sum)						):.1f}"""						)






def        __lowerCAmelCase		(	__lowerCamelCase						:     str						)	->    tuple[dict, dict]:
					__lowerCAmelCase						 =Counter()  # type: ignore
					__lowerCAmelCase						 =Counter()  # type: ignore
					single_char_strings[text[-1]] += 1

					# first case when we have space at start.
					two_char_strings[" " + text[0]] += 1
					for i in range(0					, len(__lowerCamelCase						) - 1						):
										single_char_strings[text[i]] += 1
										two_char_strings[text[i : i + 2]] += 1
					return single_char_strings, two_char_strings






def        __lowerCAmelCase		(	)	->    str:
					import doctest

					doctest.testmod()
					# text = (
					#     "Had repulsive dashwoods suspicion sincerity but advantage now him. Remark "
					#     "easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest "
					#     "jointure saw horrible. He private he on be imagine suppose. Fertile "
					#     "beloved evident through no service elderly is. Blind there if every no so "
					#     "at. Own neglected you preferred way sincerity delivered his attempted. To "
					#     "of message cottage windows do besides against uncivil.  Delightful "
					#     "unreserved impossible few estimating men favourable see entreaties. She "
					#     "propriety immediate was improving. He or entrance humoured likewise "
					#     "moderate. Much nor game son say feel. Fat make met can must form into "
					#     "gate. Me we offending prevailed discovery. "
					# )

					# calculate_prob(text)


if __name__ == "__main__":
				main()




