





"""simple docstring"""
import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PaintByExamplePipeline, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.paint_by_example import PaintByExampleImageEncoder
from diffusers.utils import floats_tensor, load_image, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()






class       _SCREAMING_SNAKE_CASE(     A					,			unittest.TestCase						):
       SCREAMING_SNAKE_CASE_     :   List[Any]					=						PaintByExamplePipeline
       SCREAMING_SNAKE_CASE_     :   int					=						IMAGE_GUIDED_IMAGE_INPAINTING_PARAMS
       SCREAMING_SNAKE_CASE_     :   Optional[Any]					=						IMAGE_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
       SCREAMING_SNAKE_CASE_     :   int					=						frozenset([]						)  # TO_DO: update the image_prams once refactored VaeImageProcessor.preprocess




       def 					_UpperCamelCase  (		self							)    ->   Optional[int]:





             """simple docstring"""






             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE     :Any	       =						UNetaDConditionModel(
                 block_out_channels=(32, 64)	,layers_per_block=2	,sample_size=32	,in_channels=9	,out_channels=4	,down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')	,up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')	,cross_attention_dim=32	,)
             __SCREAMING_SNAKE_CASE     :List[str]	       =						PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE__							)
             torch.manual_seed(0							)
             __SCREAMING_SNAKE_CASE     :Dict	       =						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							)
             __SCREAMING_SNAKE_CASE     :Dict	       =						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	,)
             __SCREAMING_SNAKE_CASE     :str	       =						PaintByExampleImageEncoder(SCREAMING_SNAKE_CASE__	,proj_size=32							)
             __SCREAMING_SNAKE_CASE     :Tuple	       =						CLIPImageProcessor(crop_size=32	,size=32							)

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




       def 					_UpperCamelCase  (		self	,SCREAMING_SNAKE_CASE__							)    ->   str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						np.array(image.convert('''RGB'''							)							)
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						image[None].transpose(0	,3	,1	,2							)
             __SCREAMING_SNAKE_CASE     :Tuple	       =						torch.from_numpy(SCREAMING_SNAKE_CASE__							).to(dtype=torch.floataa							) / 1_2_7.5 - 1.0
             return image




       def 					_UpperCamelCase  (		self	,SCREAMING_SNAKE_CASE__="cpu"	,SCREAMING_SNAKE_CASE__=0							)    ->   List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :List[Any]	       =						floats_tensor((1, 3, 32, 32)	,rng=random.Random(SCREAMING_SNAKE_CASE__							)							).to(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :int	       =						image.cpu().permute(0	,2	,3	,1							)[0]
             __SCREAMING_SNAKE_CASE     :List[Any]	       =						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__							)							).convert('''RGB'''							).resize((64, 64)							)
             __SCREAMING_SNAKE_CASE     :int	       =						Image.fromarray(np.uinta(image + 4							)							).convert('''RGB'''							).resize((64, 64)							)
             __SCREAMING_SNAKE_CASE     :Dict	       =						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__							)							).convert('''RGB'''							).resize((32, 32)							)

             if str(SCREAMING_SNAKE_CASE__							).startswith('''mps'''							):
                   __SCREAMING_SNAKE_CASE     :Optional[int]	       =						torch.manual_seed(SCREAMING_SNAKE_CASE__							)
             else:
                   __SCREAMING_SNAKE_CASE     :Dict	       =						torch.Generator(device=SCREAMING_SNAKE_CASE__							).manual_seed(SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :Any	       =						{
                 '''example_image''': example_image,
                 '''image''': init_image,
                 '''mask_image''': mask_image,
                 '''generator''': generator,
                 '''num_inference_steps''': 2,
                 '''guidance_scale''': 6.0,
                 '''output_type''': '''numpy''',
             }
             return inputs




       def 					_UpperCamelCase  (		self							)    ->   Dict:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Tuple	       =						self.get_dummy_components()

             # make sure here that pndm scheduler skips prk
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						PaintByExamplePipeline(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :List[str]	       =						pipe.to('''cpu'''							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE     :Any	       =						self.get_dummy_inputs()
             __SCREAMING_SNAKE_CASE     :Any	       =						pipe(**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :Tuple	       =						output.images

             __SCREAMING_SNAKE_CASE     :List[Any]	       =						image[0, -3:, -3:, -1]

             assert image.shape == (1, 64, 64, 3)
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						np.array([0.4_6_8_6, 0.5_6_8_7, 0.4_0_0_7, 0.5_2_1_8, 0.5_7_4_1, 0.4_4_8_2, 0.4_9_4_0, 0.4_6_2_9, 0.4_5_0_3]							)

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




       def 					_UpperCamelCase  (		self							)    ->   int:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						'''cpu'''
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						self.get_dummy_inputs()
             inputs.pop('''mask_image'''							)
             __SCREAMING_SNAKE_CASE     :Dict	       =						self.convert_to_pt(inputs.pop('''image'''							)							)
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						image.clamp(0	,1							) / 2

             # make sure here that pndm scheduler skips prk
             __SCREAMING_SNAKE_CASE     :Any	       =						PaintByExamplePipeline(**self.get_dummy_components()							)
             __SCREAMING_SNAKE_CASE     :int	       =						pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE     :str	       =						pipe(image=SCREAMING_SNAKE_CASE__	,mask_image=mask_image[:, 0]	,**SCREAMING_SNAKE_CASE__							)
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						output.images

             __SCREAMING_SNAKE_CASE     :List[Any]	       =						image.cpu().permute(0	,2	,3	,1							)[0]
             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						mask_image.cpu().permute(0	,2	,3	,1							)[0]

             __SCREAMING_SNAKE_CASE     :Dict	       =						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__							)							).convert('''RGB'''							)
             __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						Image.fromarray(np.uinta(SCREAMING_SNAKE_CASE__							)							).convert('''RGB'''							)

             __SCREAMING_SNAKE_CASE     :Tuple	       =						pipe(**self.get_dummy_inputs()							)
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						output.images

             assert out_a.shape == (1, 64, 64, 3)
             assert np.abs(out_a.flatten() - out_a.flatten()							).max() < 5E-2




       def 					_UpperCamelCase  (		self							)    ->   List[str]:





             """simple docstring"""






             super().test_inference_batch_single_identical(expected_max_diff=3E-3							)






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




       def 					_UpperCamelCase  (		self							)    ->   Dict:





             """simple docstring"""






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




       def 					_UpperCamelCase  (		self							)    ->   List[str]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE     :str	       =						load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/paint_by_example/dog_in_bucket.png'''							)
             __SCREAMING_SNAKE_CASE     :str	       =						load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/paint_by_example/mask.png'''							)
             __SCREAMING_SNAKE_CASE     :List[Any]	       =						load_image(
                 '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
                 '''/paint_by_example/panda.jpg'''							)

             __SCREAMING_SNAKE_CASE     :Any	       =						PaintByExamplePipeline.from_pretrained('''Fantasy-Studio/Paint-by-Example'''							)
             __SCREAMING_SNAKE_CASE     :Tuple	       =						pipe.to(SCREAMING_SNAKE_CASE__							)
             pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE__							)

             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						torch.manual_seed(3_21							)
             __SCREAMING_SNAKE_CASE     :Union[str, Any]	       =						pipe(
                 image=SCREAMING_SNAKE_CASE__	,mask_image=SCREAMING_SNAKE_CASE__	,example_image=SCREAMING_SNAKE_CASE__	,generator=SCREAMING_SNAKE_CASE__	,guidance_scale=5.0	,num_inference_steps=50	,output_type='''np'''	,)

             __SCREAMING_SNAKE_CASE     :Optional[int]	       =						output.images

             __SCREAMING_SNAKE_CASE     :Dict	       =						image[0, -3:, -3:, -1]

             assert image.shape == (1, 5_12, 5_12, 3)
             __SCREAMING_SNAKE_CASE     :List[str]	       =						np.array([0.4_8_3_4, 0.4_8_1_1, 0.4_8_7_4, 0.5_1_2_2, 0.5_0_8_1, 0.5_1_4_4, 0.5_2_9_1, 0.5_2_9_0, 0.5_3_7_4]							)

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






"""simple docstring"""
import math
from collections.abc import Generator



def   __lowerCamelCase     (							a_  :	int							)    ->   Generator[int, None, None]:
      __SCREAMING_SNAKE_CASE     :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   __lowerCamelCase     (							a_  :	int							)    ->   Generator[int, None, None]:
      __SCREAMING_SNAKE_CASE     :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)
            __SCREAMING_SNAKE_CASE     :Tuple	       =						int(math.sqrt(a_							)							) + 1
            for j in range(2				,     a_							):
                  if (i % j) == 0:
                        break
            else:
                  yield i



def   __lowerCamelCase     (							a_  :	int							)    ->   Generator[int, None, None]:
      __SCREAMING_SNAKE_CASE     :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):
            __SCREAMING_SNAKE_CASE     :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   __lowerCamelCase     (							)    ->   Union[str, Any]:
      from timeit import timeit

      __SCREAMING_SNAKE_CASE     :Optional[Any]	       =						'''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_          =	int(input("Calculate primes up to:\n>> ").strip())
  for ret in primes(number):
    print(ret)
  benchmark()