"""simple docstring"""






import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 							snake_case			(					__UpperCAmelCase ,       __UpperCAmelCase ,       __UpperCAmelCase ,       unittest.TestCase							):




					"""simple docstring"""

					snake_case__							       =					StableDiffusionImageVariationPipeline
					snake_case__							       =					IMAGE_VARIATION_PARAMS
					snake_case__							       =					IMAGE_VARIATION_BATCH_PARAMS
					snake_case__							       =					frozenset([]							)
					# TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
					snake_case__							       =					frozenset([]							)







					def 						__lowerCAmelCase		(							self  :      Optional[Any]     ):
									torch.manual_seed(0     )
									UpperCAmelCase__			 =				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       ,)
									UpperCAmelCase__			 =				PNDMScheduler(skip_prk_steps=lowerCamelCase__     )
									torch.manual_seed(0     )
									UpperCAmelCase__			 =				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       ,)
									torch.manual_seed(0     )
									UpperCAmelCase__			 =				CLIPVisionConfig(
									    hidden_size=32       ,projection_dim=32       ,intermediate_size=37       ,layer_norm_eps=1e-05       ,num_attention_heads=4       ,num_hidden_layers=5       ,image_size=32       ,patch_size=4       ,)
									UpperCAmelCase__			 =				CLIPVisionModelWithProjection(lowerCamelCase__     )
									UpperCAmelCase__			 =				CLIPImageProcessor(crop_size=32       ,size=32     )

									UpperCAmelCase__			 =				{
									    'unet': unet,
									    'scheduler': scheduler,
									    'vae': vae,
									    'image_encoder': image_encoder,
									    'feature_extractor': feature_extractor,
									    'safety_checker': None,
									}
									return components







					def 						__lowerCAmelCase		(							self  :      Optional[int]       ,lowerCamelCase__  :      Tuple       ,lowerCamelCase__  :      str=0     ):
									UpperCAmelCase__			 =				floats_tensor((1, 3, 32, 32)       ,rng=random.Random(lowerCamelCase__     )     )
									UpperCAmelCase__			 =				image.cpu().permute(0       ,2       ,3       ,1     )[0]
									UpperCAmelCase__			 =				Image.fromarray(np.uinta(lowerCamelCase__     )     ).convert('RGB'     ).resize((32, 32)     )
									if str(lowerCamelCase__     ).startswith('mps'     ):
													UpperCAmelCase__			 =				torch.manual_seed(lowerCamelCase__     )
									else:
													UpperCAmelCase__			 =				torch.Generator(device=lowerCamelCase__     ).manual_seed(lowerCamelCase__     )
									UpperCAmelCase__			 =				{
									    'image': image,
									    'generator': generator,
									    'num_inference_steps': 2,
									    'guidance_scale': 6.0,
									    'output_type': 'numpy',
									}
									return inputs







					def 						__lowerCAmelCase		(							self  :      Optional[Any]     ):
									UpperCAmelCase__			 =				'cpu'  # ensure determinism for the device-dependent torch.Generator
									UpperCAmelCase__			 =				self.get_dummy_components()
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline(**lowerCamelCase__     )
									UpperCAmelCase__			 =				sd_pipe.to(lowerCamelCase__     )
									sd_pipe.set_progress_bar_config(disable=lowerCamelCase__     )

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

									assert image.shape == (1, 64, 64, 3)
									UpperCAmelCase__			 =				np.array([0.5_2_3_9, 0.5_7_2_3, 0.4_7_9_6, 0.5_0_4_9, 0.5_5_5_0, 0.4_6_8_5, 0.5_3_2_9, 0.4_8_9_1, 0.4_9_2_1]     )

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







					def 						__lowerCAmelCase		(							self  :      int     ):
									UpperCAmelCase__			 =				'cpu'  # ensure determinism for the device-dependent torch.Generator
									UpperCAmelCase__			 =				self.get_dummy_components()
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline(**lowerCamelCase__     )
									UpperCAmelCase__			 =				sd_pipe.to(lowerCamelCase__     )
									sd_pipe.set_progress_bar_config(disable=lowerCamelCase__     )

									UpperCAmelCase__			 =				self.get_dummy_inputs(lowerCamelCase__     )
									UpperCAmelCase__			 =				2 * [inputs['image']]
									UpperCAmelCase__			 =				sd_pipe(**lowerCamelCase__     )

									UpperCAmelCase__			 =				output.images

									UpperCAmelCase__			 =				image[-1, -3:, -3:, -1]

									assert image.shape == (2, 64, 64, 3)
									UpperCAmelCase__			 =				np.array([0.6_8_9_2, 0.5_6_3_7, 0.5_8_3_6, 0.5_7_7_1, 0.6_2_5_4, 0.6_4_0_9, 0.5_5_8_0, 0.5_5_6_9, 0.5_2_8_9]     )

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







					def 						__lowerCAmelCase		(							self  :      Optional[Any]     ):
									super().test_inference_batch_single_identical(expected_max_diff=3e-3     )






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




					"""simple docstring"""

					def 						__lowerCAmelCase		(							self  :      str     ):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







					def 						__lowerCAmelCase		(							self  :      Dict       ,lowerCamelCase__  :      int       ,lowerCamelCase__  :      Optional[Any]="cpu"       ,lowerCamelCase__  :      str=torch.floataa       ,lowerCamelCase__  :      Dict=0     ):
									UpperCAmelCase__			 =				torch.Generator(device=lowerCamelCase__     ).manual_seed(lowerCamelCase__     )
									UpperCAmelCase__			 =				load_image(
									    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
									    '/stable_diffusion_imgvar/input_image_vermeer.png'     )
									UpperCAmelCase__			 =				np.random.RandomState(lowerCamelCase__     ).standard_normal((1, 4, 64, 64)     )
									UpperCAmelCase__			 =				torch.from_numpy(lowerCamelCase__     ).to(device=lowerCamelCase__       ,dtype=lowerCamelCase__     )
									UpperCAmelCase__			 =				{
									    'image': init_image,
									    'latents': latents,
									    'generator': generator,
									    'num_inference_steps': 3,
									    'guidance_scale': 7.5,
									    'output_type': 'numpy',
									}
									return inputs







					def 						__lowerCAmelCase		(							self  :      Union[str, Any]     ):
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline.from_pretrained(
									    'lambdalabs/sd-image-variations-diffusers'       ,safety_checker=lowerCamelCase__     )
									UpperCAmelCase__			 =				sd_pipe.to(lowerCamelCase__     )
									sd_pipe.set_progress_bar_config(disable=lowerCamelCase__     )

									UpperCAmelCase__			 =				self.get_inputs(lowerCamelCase__     )
									UpperCAmelCase__			 =				sd_pipe(**lowerCamelCase__     ).images
									UpperCAmelCase__			 =				image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 512, 512, 3)
									UpperCAmelCase__			 =				np.array([0.8_4_4_9_1, 0.9_0_7_8_9, 0.7_5_7_0_8, 0.7_8_7_3_4, 0.8_3_4_8_5, 0.7_0_0_9_9, 0.6_6_9_3_8, 0.6_8_7_2_7, 0.6_1_3_7_9]     )
									assert np.abs(image_slice - expected_slice     ).max() < 6e-3







					def 						__lowerCAmelCase		(							self  :      int     ):
									UpperCAmelCase__			 =				0

									def callback_fn(lowerCamelCase__  :      int       ,lowerCamelCase__  :      int       ,lowerCamelCase__  :      torch.FloatTensor     ) -> None:
													UpperCAmelCase__			 =				True
													nonlocal number_of_steps
													number_of_steps += 1
													if step == 1:
																	UpperCAmelCase__			 =				latents.detach().cpu().numpy()
																	assert latents.shape == (1, 4, 64, 64)
																	UpperCAmelCase__			 =				latents[0, -3:, -3:, -1]
																	UpperCAmelCase__			 =				np.array(
																	    [-0.1_6_2_1, 0.2_8_3_7, -0.7_9_7_9, -0.1_2_2_1, -1.3_0_5_7, 0.7_6_8_1, -2.1_1_9_1, 0.0_4_6_4, 1.6_3_0_9]     )

																	assert np.abs(latents_slice.flatten() - expected_slice     ).max() < 5e-2
													elif step == 2:
																	UpperCAmelCase__			 =				latents.detach().cpu().numpy()
																	assert latents.shape == (1, 4, 64, 64)
																	UpperCAmelCase__			 =				latents[0, -3:, -3:, -1]
																	UpperCAmelCase__			 =				np.array([0.6_2_9_9, 1.7_5_0_0, 1.1_9_9_2, -2.1_5_8_2, -1.8_9_9_4, 0.7_3_3_4, -0.7_0_9_0, 1.0_1_3_7, 1.5_2_7_3]     )

																	assert np.abs(latents_slice.flatten() - expected_slice     ).max() < 5e-2

									UpperCAmelCase__			 =				False

									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline.from_pretrained(
									    'fusing/sd-image-variations-diffusers'       ,safety_checker=lowerCamelCase__       ,torch_dtype=torch.floataa       ,)
									pipe.to(lowerCamelCase__     )
									pipe.set_progress_bar_config(disable=lowerCamelCase__     )
									pipe.enable_attention_slicing()

									UpperCAmelCase__			 =				self.get_inputs(lowerCamelCase__       ,dtype=torch.floataa     )
									pipe(**lowerCamelCase__       ,callback=lowerCamelCase__       ,callback_steps=1     )
									assert callback_fn.has_been_called
									assert number_of_steps == inputs["num_inference_steps"]







					def 						__lowerCAmelCase		(							self  :      int     ):
									torch.cuda.empty_cache()
									torch.cuda.reset_max_memory_allocated()
									torch.cuda.reset_peak_memory_stats()

									UpperCAmelCase__			 =				'fusing/sd-image-variations-diffusers'
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline.from_pretrained(
									    lowerCamelCase__       ,safety_checker=lowerCamelCase__       ,torch_dtype=torch.floataa     )
									UpperCAmelCase__			 =				pipe.to(lowerCamelCase__     )
									pipe.set_progress_bar_config(disable=lowerCamelCase__     )
									pipe.enable_attention_slicing(1     )
									pipe.enable_sequential_cpu_offload()

									UpperCAmelCase__			 =				self.get_inputs(lowerCamelCase__       ,dtype=torch.floataa     )
									UpperCAmelCase__			 =				pipe(**lowerCamelCase__     )

									UpperCAmelCase__			 =				torch.cuda.max_memory_allocated()
									# make sure that less than 2.6 GB is allocated
									assert mem_bytes < 2.6 * 10**9






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




					"""simple docstring"""

					def 						__lowerCAmelCase		(							self  :      List[str]     ):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()







					def 						__lowerCAmelCase		(							self  :      Union[str, Any]       ,lowerCamelCase__  :      Any       ,lowerCamelCase__  :      Optional[Any]="cpu"       ,lowerCamelCase__  :      Dict=torch.floataa       ,lowerCamelCase__  :      Dict=0     ):
									UpperCAmelCase__			 =				torch.Generator(device=lowerCamelCase__     ).manual_seed(lowerCamelCase__     )
									UpperCAmelCase__			 =				load_image(
									    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
									    '/stable_diffusion_imgvar/input_image_vermeer.png'     )
									UpperCAmelCase__			 =				np.random.RandomState(lowerCamelCase__     ).standard_normal((1, 4, 64, 64)     )
									UpperCAmelCase__			 =				torch.from_numpy(lowerCamelCase__     ).to(device=lowerCamelCase__       ,dtype=lowerCamelCase__     )
									UpperCAmelCase__			 =				{
									    'image': init_image,
									    'latents': latents,
									    'generator': generator,
									    'num_inference_steps': 50,
									    'guidance_scale': 7.5,
									    'output_type': 'numpy',
									}
									return inputs







					def 						__lowerCAmelCase		(							self  :      Union[str, Any]     ):
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline.from_pretrained('fusing/sd-image-variations-diffusers'     )
									sd_pipe.to(lowerCamelCase__     )
									sd_pipe.set_progress_bar_config(disable=lowerCamelCase__     )

									UpperCAmelCase__			 =				self.get_inputs(lowerCamelCase__     )
									UpperCAmelCase__			 =				sd_pipe(**lowerCamelCase__     ).images[0]

									UpperCAmelCase__			 =				load_numpy(
									    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
									    '/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy'     )
									UpperCAmelCase__			 =				np.abs(expected_image - image     ).max()
									assert max_diff < 1e-3







					def 						__lowerCAmelCase		(							self  :      int     ):
									UpperCAmelCase__			 =				StableDiffusionImageVariationPipeline.from_pretrained('fusing/sd-image-variations-diffusers'     )
									UpperCAmelCase__			 =				DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config     )
									sd_pipe.to(lowerCamelCase__     )
									sd_pipe.set_progress_bar_config(disable=lowerCamelCase__     )

									UpperCAmelCase__			 =				self.get_inputs(lowerCamelCase__     )
									UpperCAmelCase__			 =				25
									UpperCAmelCase__			 =				sd_pipe(**lowerCamelCase__     ).images[0]

									UpperCAmelCase__			 =				load_numpy(
									    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'
									    '/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy'     )
									UpperCAmelCase__			 =				np.abs(expected_image - image     ).max()
									assert max_diff < 1e-3




"""simple docstring"""






from __future__ import annotations



def     a_		(   lowerCamelCase			):
				for r in range(1   ,     lowerCamelCase			):
								UpperCAmelCase__			 =				[]
								for x in range(n - 1			):
												UpperCAmelCase__			 =				pow(lowerCamelCase   ,     lowerCamelCase   ,     lowerCamelCase			)
												if val in li:
																break
												li.append(lowerCamelCase			)
								else:
												return r
				return None


if __name__ == "__main__":
						lowerCAmelCase__    :    Any			=      int(input('Enter a prime number q: '))
						lowerCAmelCase__    :    List[str]			=      find_primitive(q)
						if a is None:
												print(F"""Cannot find the primitive for the value: {a!r}""")
						else:
												lowerCAmelCase__    :    str			=      int(input('Enter private key of A: '))
												lowerCAmelCase__    :    List[Any]			=      pow(a, a_private, q)
												lowerCAmelCase__    :    List[str]			=      int(input('Enter private key of B: '))
												lowerCAmelCase__    :    Any			=      pow(a, b_private, q)

												lowerCAmelCase__    :    Union[str, Any]			=      pow(b_public, a_private, q)
												lowerCAmelCase__    :    Tuple			=      pow(a_public, b_private, q)

												print('The key value generated by A is: ', a_secret)
												print('The key value generated by B is: ', b_secret)



