import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()
class   _lowerCAmelCase		(     unittest.TestCase				):







							def 				snake_case  (				self     :    Union[str, Any]		):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







							@property
							def 				snake_case  (				self     :    Optional[int]		):
										lowerCamelCase						:Union[str, Any]						  =     1
										lowerCamelCase						:Dict						  =     3
										lowerCamelCase						:Any						  =     (32, 32)

										lowerCamelCase						:Union[str, Any]						  =     floats_tensor((batch_size, num_channels) + sizes	,					rng=random.Random(0		)		).to(__snake_case		)
										return image







							@property
							def 				snake_case  (				self     :    Tuple		):
										torch.manual_seed(0		)
										lowerCamelCase						:Tuple						  =     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 				snake_case  (				self     :    List[Any]		):
										torch.manual_seed(0		)
										lowerCamelCase						:Optional[int]						  =     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 				snake_case  (				self     :    str		):
										torch.manual_seed(0		)
										lowerCamelCase						:Dict						  =     RobertaSeriesConfig(
										    hidden_size=32	,					project_dim=32	,					intermediate_size=37	,					layer_norm_eps=1e-0_5	,					num_attention_heads=4	,					num_hidden_layers=5	,					pad_token_id=1	,					vocab_size=5006	,					)
										return RobertaSeriesModelWithTransformation(__snake_case		)







							@property
							def 				snake_case  (				self     :    List[Any]		):
										def extract(*__snake_case     :    Dict	,					**__snake_case     :    Optional[Any]		):
													class   _lowerCAmelCase		:







																				def __init__(				self     :    List[str]		):
																							lowerCamelCase						:Optional[Any]						  =     torch.ones([0]		)







																				def 				snake_case  (				self     :    Tuple	,					__snake_case     :    Any		):
																							self.pixel_values.to(__snake_case		)
																							return self


													return Out()

										return extract







							def 				snake_case  (				self     :    str		):
										lowerCamelCase						:Optional[int]						  =     '''cpu'''  # ensure determinism for the device-dependent torch.Generator
										lowerCamelCase						:Any						  =     self.dummy_cond_unet
										lowerCamelCase						:List[str]						  =     PNDMScheduler(skip_prk_steps=__snake_case		)
										lowerCamelCase						:Any						  =     self.dummy_vae
										lowerCamelCase						:Any						  =     self.dummy_text_encoder
										lowerCamelCase						:Union[str, Any]						  =     XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''		)
										lowerCamelCase						:Union[str, Any]						  =     77

										lowerCamelCase						:Optional[Any]						  =     self.dummy_image.to(__snake_case		)
										lowerCamelCase						:int						  =     init_image / 2 + 0.5

										# make sure here that pndm scheduler skips prk
										lowerCamelCase						:List[str]						  =     AltDiffusionImgaImgPipeline(
										    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	,					)
										lowerCamelCase						:str						  =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor	,					do_normalize=__snake_case		)
										lowerCamelCase						:List[Any]						  =     alt_pipe.to(__snake_case		)
										alt_pipe.set_progress_bar_config(disable=__snake_case		)

										lowerCamelCase						:str						  =     '''A painting of a squirrel eating a burger'''
										lowerCamelCase						:Tuple						  =     torch.Generator(device=__snake_case		).manual_seed(0		)
										lowerCamelCase						:List[Any]						  =     alt_pipe(
										    [prompt]	,					generator=__snake_case	,					guidance_scale=6.0	,					num_inference_steps=2	,					output_type='''np'''	,					image=__snake_case	,					)

										lowerCamelCase						:List[Any]						  =     output.images

										lowerCamelCase						:Tuple						  =     torch.Generator(device=__snake_case		).manual_seed(0		)
										lowerCamelCase						:Tuple						  =     alt_pipe(
										    [prompt]	,					generator=__snake_case	,					guidance_scale=6.0	,					num_inference_steps=2	,					output_type='''np'''	,					image=__snake_case	,					return_dict=__snake_case	,					)[0]

										lowerCamelCase						:str						  =     image[0, -3:, -3:, -1]
										lowerCamelCase						:Any						  =     image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 32, 32, 3)
										lowerCamelCase						:str						  =     np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]		)

										assert np.abs(image_slice.flatten() - expected_slice		).max() < 5e-3
										assert np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 5e-3







							@unittest.skipIf(torch_device != '''cuda'''	,					'''This test requires a GPU'''		)
							def 				snake_case  (				self     :    Optional[Any]		):
										lowerCamelCase						:int						  =     self.dummy_cond_unet
										lowerCamelCase						:str						  =     PNDMScheduler(skip_prk_steps=__snake_case		)
										lowerCamelCase						:Union[str, Any]						  =     self.dummy_vae
										lowerCamelCase						:Optional[Any]						  =     self.dummy_text_encoder
										lowerCamelCase						:int						  =     XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''		)
										lowerCamelCase						:Any						  =     77

										lowerCamelCase						:Tuple						  =     self.dummy_image.to(__snake_case		)

										# put models in fp16
										lowerCamelCase						:Any						  =     unet.half()
										lowerCamelCase						:List[str]						  =     vae.half()
										lowerCamelCase						:Any						  =     bert.half()

										# make sure here that pndm scheduler skips prk
										lowerCamelCase						:int						  =     AltDiffusionImgaImgPipeline(
										    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	,					)
										lowerCamelCase						:Dict						  =     VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor	,					do_normalize=__snake_case		)
										lowerCamelCase						:List[Any]						  =     alt_pipe.to(__snake_case		)
										alt_pipe.set_progress_bar_config(disable=__snake_case		)

										lowerCamelCase						:List[Any]						  =     '''A painting of a squirrel eating a burger'''
										lowerCamelCase						:Optional[int]						  =     torch.manual_seed(0		)
										lowerCamelCase						:Optional[int]						  =     alt_pipe(
										    [prompt]	,					generator=__snake_case	,					num_inference_steps=2	,					output_type='''np'''	,					image=__snake_case	,					).images

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







							@unittest.skipIf(torch_device != '''cuda'''	,					'''This test requires a GPU'''		)
							def 				snake_case  (				self     :    List[Any]		):
										lowerCamelCase						:Any						  =     load_image(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
										    '''/img2img/sketch-mountains-input.jpg'''		)
										# resize to resolution that is divisible by 8 but not 16 or 32
										lowerCamelCase						:Optional[int]						  =     init_image.resize((760, 504)		)

										lowerCamelCase						:Any						  =     '''BAAI/AltDiffusion'''
										lowerCamelCase						:Tuple						  =     AltDiffusionImgaImgPipeline.from_pretrained(
										    __snake_case	,					safety_checker=__snake_case	,					)
										pipe.to(__snake_case		)
										pipe.set_progress_bar_config(disable=__snake_case		)
										pipe.enable_attention_slicing()

										lowerCamelCase						:List[Any]						  =     '''A fantasy landscape, trending on artstation'''

										lowerCamelCase						:Union[str, Any]						  =     torch.manual_seed(0		)
										lowerCamelCase						:Tuple						  =     pipe(
										    prompt=__snake_case	,					image=__snake_case	,					strength=0.7_5	,					guidance_scale=7.5	,					generator=__snake_case	,					output_type='''np'''	,					)
										lowerCamelCase						:Any						  =     output.images[0]

										lowerCamelCase						:Tuple						  =     image[255:258, 383:386, -1]

										assert image.shape == (504, 760, 3)
										lowerCamelCase						:List[str]						  =     np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]		)

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


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







							def 				snake_case  (				self     :    Optional[Any]		):
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()







							def 				snake_case  (				self     :    int		):
										lowerCamelCase						:List[Any]						  =     load_image(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
										    '''/img2img/sketch-mountains-input.jpg'''		)
										lowerCamelCase						:List[str]						  =     init_image.resize((768, 512)		)
										lowerCamelCase						:Optional[Any]						  =     load_numpy(
										    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'''		)

										lowerCamelCase						:str						  =     '''BAAI/AltDiffusion'''
										lowerCamelCase						:List[Any]						  =     AltDiffusionImgaImgPipeline.from_pretrained(
										    __snake_case	,					safety_checker=__snake_case	,					)
										pipe.to(__snake_case		)
										pipe.set_progress_bar_config(disable=__snake_case		)
										pipe.enable_attention_slicing()

										lowerCamelCase						:Any						  =     '''A fantasy landscape, trending on artstation'''

										lowerCamelCase						:int						  =     torch.manual_seed(0		)
										lowerCamelCase						:List[Any]						  =     pipe(
										    prompt=__snake_case	,					image=__snake_case	,					strength=0.7_5	,					guidance_scale=7.5	,					generator=__snake_case	,					output_type='''np'''	,					)
										lowerCamelCase						:Dict						  =     output.images[0]

										assert image.shape == (512, 768, 3)
										# img2img is flaky across GPUs even in fp32, so using MAE here
										assert np.abs(expected_image - image		).max() < 1e-2




import math





def  _lowerCamelCase					(   a_				: int):

			if 1 < number < 4:
						# 2 and 3 are primes
						return True
			elif number < 2 or number % 2 == 0 or number % 3 == 0:
						# Negatives, 0, 1, all even numbers, all multiples of 3 are not primes
						return False

			# All primes number are in format of 6k +/- 1
			for i in range(5						,			int(math.sqrt(a_) + 1)						,			6):
						if number % i == 0 or number % (i + 2) == 0:
									return False
			return True





def  _lowerCamelCase					(   a_				: float = 0.1):
			lowerCamelCase						:Dict						  =     3
			lowerCamelCase						:List[Any]						  =     3

			while primes / (2 * j - 1) >= ratio:
						for i in range(j * j + j + 1						,			(j + 2) * (j + 2)						,			j + 1):
									primes += is_prime(a_)
						j += 2
			return j


if __name__ == "__main__":
			import doctest

			doctest.testmod()



