import gc
import unittest

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

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

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()



class     snake_case_			(						__A    ,__A    ,unittest.TestCase			):
   __A      :						List[str]   =							StableDiffusionXLPipeline
   __A      :						str   =							TEXT_TO_IMAGE_PARAMS
   __A      :						Optional[int]   =							TEXT_TO_IMAGE_BATCH_PARAMS
   __A      :						Optional[Any]   =							TEXT_TO_IMAGE_IMAGE_PARAMS
   __A      :						Dict   =							TEXT_TO_IMAGE_IMAGE_PARAMS






   def  __UpperCamelCase	( self							:	Optional[Any]    )   ->		List[Any]:
       torch.manual_seed(0    )
       lowercase__					:  Dict          =							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      ,		)
       lowercase__					:  List[str]          =							EulerDiscreteScheduler(
           beta_start=0.0_00_85      ,		beta_end=0.0_12      ,		steps_offset=1      ,		beta_schedule="scaled_linear"      ,		timestep_spacing="leading"      ,		)
       torch.manual_seed(0    )
       lowercase__					:  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    )
       lowercase__					:  Optional[int]          =							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      ,		)
       lowercase__					:  Optional[int]          =							CLIPTextModel(snake_case__    )
       lowercase__					:  Optional[Any]          =							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      ,		local_files_only=snake_case__    )

       lowercase__					:  Tuple          =							CLIPTextModelWithProjection(snake_case__    )
       lowercase__					:  List[Any]          =							CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"      ,		local_files_only=snake_case__    )

       lowercase__					:  List[str]          =							{
           '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							:	Dict      ,		lowercase_							:	Tuple      ,		lowercase_							:	str=0    )   ->		int:
       if str(snake_case__    ).startswith("mps"    ):
           lowercase__					:  Dict          =							torch.manual_seed(snake_case__    )
       else:
           lowercase__					:  int          =							torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
       lowercase__					:  Optional[int]          =							{
           'prompt': 'A painting of a squirrel eating a burger',
           'generator': generator,
           'num_inference_steps': 2,
           'guidance_scale': 5.0,
           'output_type': 'numpy',
       }
       return inputs






   def  __UpperCamelCase	( self							:	List[str]    )   ->		Any:
       lowercase__					:  Any          =							'cpu'  # ensure determinism for the device-dependent torch.Generator
       lowercase__					:  Optional[Any]          =							self.get_dummy_components()
       lowercase__					:  Optional[int]          =							StableDiffusionXLPipeline(**snake_case__    )
       lowercase__					:  List[str]          =							sd_pipe.to(snake_case__    )
       sd_pipe.set_progress_bar_config(disable=snake_case__    )

       lowercase__					:  Optional[int]          =							self.get_dummy_inputs(snake_case__    )
       lowercase__					:  List[str]          =							sd_pipe(**snake_case__    ).images
       lowercase__					:  Union[str, Any]          =							image[0, -3:, -3:, -1]

       assert image.shape == (1, 64, 64, 3)
       lowercase__					:  List[str]          =							np.array([0.58_73, 0.61_28, 0.47_97, 0.51_22, 0.56_74, 0.46_39, 0.52_27, 0.51_49, 0.47_47]    )

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






   def  __UpperCamelCase	( self							:	Any    )   ->		List[Any]:
       lowercase__					:  Any          =							self.get_dummy_components()
       lowercase__					:  str          =							StableDiffusionXLPipeline(**snake_case__    )
       lowercase__					:  Any          =							sd_pipe.to(snake_case__    )
       lowercase__					:  List[str]          =							sd_pipe.to(snake_case__    )
       sd_pipe.set_progress_bar_config(disable=snake_case__    )

       # forward without prompt embeds
       lowercase__					:  int          =							self.get_dummy_inputs(snake_case__    )
       lowercase__					:  int          =							3 * ['this is a negative prompt']
       lowercase__					:  Union[str, Any]          =							negative_prompt
       lowercase__					:  int          =							3 * [inputs['prompt']]

       lowercase__					:  Optional[int]          =							sd_pipe(**snake_case__    )
       lowercase__					:  int          =							output.images[0, -3:, -3:, -1]

       # forward with prompt embeds
       lowercase__					:  str          =							self.get_dummy_inputs(snake_case__    )
       lowercase__					:  Union[str, Any]          =							3 * ['this is a negative prompt']
       lowercase__					:  Optional[int]          =							3 * [inputs.pop("prompt"    )]

       (
           lowercase__ 
       )					:  Dict          =							sd_pipe.encode_prompt(snake_case__      ,		negative_prompt=snake_case__    )

       lowercase__					:  Optional[int]          =							sd_pipe(
           **snake_case__      ,		prompt_embeds=snake_case__      ,		negative_prompt_embeds=snake_case__      ,		pooled_prompt_embeds=snake_case__      ,		negative_pooled_prompt_embeds=snake_case__      ,		)
       lowercase__					:  Tuple          =							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






   def  __UpperCamelCase	( self							:	List[Any]    )   ->		int:
       super().test_attention_slicing_forward_pass(expected_max_diff=3E-3    )







   def  __UpperCamelCase	( self							:	List[Any]    )   ->		str:
       super().test_inference_batch_single_identical(expected_max_diff=3E-3    )



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






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






   def  __UpperCamelCase	( self							:	Any      ,		lowercase_							:	str      ,		lowercase_							:	List[Any]="cpu"      ,		lowercase_							:	Union[str, Any]=torch.floataa      ,		lowercase_							:	Dict=0    )   ->		int:
       lowercase__					:  Any          =							torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
       lowercase__					:  List[Any]          =							np.random.RandomState(snake_case__    ).standard_normal((1, 4, 64, 64)    )
       lowercase__					:  Dict          =							torch.from_numpy(snake_case__    ).to(device=snake_case__      ,		dtype=snake_case__    )
       lowercase__					:  int          =							{
           '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							:	Optional[int]    )   ->		Any:
       lowercase__					:  Union[str, Any]          =							DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"    )
       pipe.to(snake_case__    )
       pipe.set_progress_bar_config(disable=snake_case__    )

       lowercase__					:  List[Any]          =							self.get_inputs(snake_case__    )
       lowercase__					:  Optional[Any]          =							pipe(**snake_case__    ).images
       lowercase__					:  Dict          =							image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 5_12, 5_12, 3)
       lowercase__					:  Dict          =							np.array([0.4_94_93, 0.4_78_96, 0.4_07_98, 0.5_42_14, 0.5_32_12, 0.4_82_02, 0.4_76_56, 0.4_63_29, 0.4_85_06]    )
       assert np.abs(image_slice - expected_slice    ).max() < 7E-3







'''simple docstring'''




import math
from collections.abc import Generator

def       __UpperCamelCase     (     _A     :					int					)     ->   Generator[int, None, None]:




	"""simple docstring"""





	lowerCAmelCase       :     Generator   				=			(i for i in range(1       , (max_n + 1)					))
	for i in (n for n in numbers if n > 1):
		for j in range(2       , _A					):
			if (i % j) == 0:
				break
		else:
			yield i

def       __UpperCamelCase     (     _A     :					int					)     ->   Generator[int, None, None]:




	"""simple docstring"""





	lowerCAmelCase       :     Generator   				=			(i for i in range(1       , (max_n + 1)					))
	for i in (n for n in numbers if n > 1):
		# only need to check for factors up to sqrt(i)
		lowerCAmelCase       :     List[str]   				=			int(math.sqrt(_A					)					) + 1
		for j in range(2       , _A					):
			if (i % j) == 0:
				break
		else:
			yield i

def       __UpperCamelCase     (     _A     :					int					)     ->   Generator[int, None, None]:




	"""simple docstring"""





	lowerCAmelCase       :     Generator   				=			(i for i in range(1       , (max_n + 1)       , 2					))
	# It's useless to test even numbers as they will not be prime
	if max_n > 2:
		yield 2  # Because 2 will not be tested, it's necessary to yield it now
	for i in (n for n in numbers if n > 1):
		lowerCAmelCase       :     int   				=			int(math.sqrt(_A					)					) + 1
		for j in range(3       , _A       , 2					):
			# As we removed the even numbers, we don't need them now
			if (i % j) == 0:
				break
		else:
			yield i

def       __UpperCamelCase     (     )     ->   Dict:




	"""simple docstring"""





	from timeit import timeit

	lowerCAmelCase       :     Tuple   				=			'from __main__ import slow_primes, primes, fast_primes'
	print(timeit('slow_primes(1_000_000_000_000)'       , setup=_A       , number=1_00_00_00					)					)
	print(timeit('primes(1_000_000_000_000)'       , setup=_A       , number=1_00_00_00					)					)
	print(timeit('fast_primes(1_000_000_000_000)'       , setup=_A       , number=1_00_00_00					)					)


if __name__ == "__main__":
				_lowerCAmelCase	:		Optional[Any]		  =						int(input('Calculate primes up to:\n>> ').strip())
				for ret in primes(number):
								print(ret)
				benchmark()
