

from math import sqrt

def      _lowerCamelCase	(						__A    :							int )      ->					bool:
    assert isinstance(__A		,		__A ) and (
        number >= 0
    ), "'number' must been an int and positive"

    _UpperCAmelCase				:      Union[str, Any]			  =				True

    # 0 and 1 are none primes.
    if number <= 1:
        _UpperCAmelCase				:      Dict			  =				False

    for divisor in range(2		,		int(round(sqrt(__A ) ) ) + 1 ):
        # if 'number' divisible by 'divisor' then sets 'status'
        # of false and break up the loop.
        if number % divisor == 0:
            _UpperCAmelCase				:      str			  =				False
            break

    # precondition
    assert isinstance(__A		,		__A ), "'status' must been from type bool"

    return status

def      _lowerCamelCase	(						__A    :							str )      ->					Union[str, Any]:
    assert isinstance(__A		,		__A ) and (n > 2), "'N' must been an int and > 2"

    # beginList: contains all natural numbers from 2 up to N
    _UpperCAmelCase				:      Tuple			  =				list(range(2		,		n + 1 ) )

    _UpperCAmelCase				:      Any			  =				[]  # this list will be returns.

    # actual sieve of erathostenes
    for i in range(len(__A ) ):
        for j in range(i + 1		,		len(__A ) ):
            if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
                _UpperCAmelCase				:      Any			  =				0

    # filters actual prime numbers.
    _UpperCAmelCase				:      str			  =				[x for x in begin_list if x != 0]

    # precondition
    assert isinstance(__A		,		__A ), "'ans' must been from type list"

    return ans

def      _lowerCamelCase	(						__A    :							Optional[int] )      ->					int:
    assert isinstance(__A		,		__A ) and (n > 2), "'N' must been an int and > 2"

    _UpperCAmelCase				:      Optional[Any]			  =				[]

    # iterates over all numbers between 2 up to N+1
    # if a number is prime then appends to list 'ans'
    for number in range(2		,		n + 1 ):
        if is_prime(__A ):
            ans.append(__A )

    # precondition
    assert isinstance(__A		,		__A ), "'ans' must been from type list"

    return ans

def      _lowerCamelCase	(						__A    :							Dict )      ->					Optional[int]:
    assert isinstance(__A		,		__A ) and number >= 0, "'number' must been an int and >= 0"

    _UpperCAmelCase				:      List[str]			  =				[]  # this list will be returns of the function.

    # potential prime number factors.

    _UpperCAmelCase				:      Any			  =				2

    _UpperCAmelCase				:      Any			  =				number

    if number == 0 or number == 1:
        ans.append(__A )

    # if 'number' not prime then builds the prime factorization of 'number'
    elif not is_prime(__A ):
        while quotient != 1:
            if is_prime(__A ) and (quotient % factor == 0):
                ans.append(__A )
                quotient /= factor
            else:
                factor += 1

    else:
        ans.append(__A )

    # precondition
    assert isinstance(__A		,		__A ), "'ans' must been from type list"

    return ans

def      _lowerCamelCase	(						__A    :							List[str] )      ->					str:
    assert isinstance(__A		,		__A ) and (
        number >= 0
    ), "'number' bust been an int and >= 0"

    _UpperCAmelCase				:      List[str]			  =				0

    # prime factorization of 'number'
    _UpperCAmelCase				:      Union[str, Any]			  =				prime_factorization(__A )

    _UpperCAmelCase				:      List[Any]			  =				max(__A )

    # precondition
    assert isinstance(__A		,		__A ), "'ans' must been from type int"

    return ans

def      _lowerCamelCase	(						__A    :							Optional[Any] )      ->					int:
    assert isinstance(__A		,		__A ) and (
        number >= 0
    ), "'number' bust been an int and >= 0"

    _UpperCAmelCase				:      Optional[Any]			  =				0

    # prime factorization of 'number'
    _UpperCAmelCase				:      List[Any]			  =				prime_factorization(__A )

    _UpperCAmelCase				:      List[str]			  =				min(__A )

    # precondition
    assert isinstance(__A		,		__A ), "'ans' must been from type int"

    return ans

def      _lowerCamelCase	(						__A    :							Optional[Any] )      ->					int:
    assert isinstance(__A		,		__A ), "'number' must been an int"
    assert isinstance(number % 2 == 0		,		__A ), "compare bust been from type bool"

    return number % 2 == 0

def      _lowerCamelCase	(						__A    :							str )      ->					Optional[Any]:
    assert isinstance(__A		,		__A ), "'number' must been an int"
    assert isinstance(number % 2 != 0		,		__A ), "compare bust been from type bool"

    return number % 2 != 0

def      _lowerCamelCase	(						__A    :							List[Any] )      ->					List[str]:
    assert (
        isinstance(__A		,		__A ) and (number > 2) and is_even(__A )
    ), "'number' must been an int, even and > 2"

    _UpperCAmelCase				:      str			  =				[]  # this list will returned

    # creates a list of prime numbers between 2 up to 'number'
    _UpperCAmelCase				:      List[Any]			  =				get_prime_numbers(__A )
    _UpperCAmelCase				:      Dict			  =				len(__A )

    # run variable for while-loops.
    _UpperCAmelCase				:      Dict			  =				0
    _UpperCAmelCase				:      List[Any]			  =				None

    # exit variable. for break up the loops
    _UpperCAmelCase				:      int			  =				True

    while i < len_pn and loop:
        _UpperCAmelCase				:      List[str]			  =				i + 1

        while j < len_pn and loop:
            if prime_numbers[i] + prime_numbers[j] == number:
                _UpperCAmelCase				:      Tuple			  =				False
                ans.append(prime_numbers[i] )
                ans.append(prime_numbers[j] )

            j += 1

        i += 1

    # precondition
    assert (
        isinstance(__A		,		__A )
        and (len(__A ) == 2)
        and (ans[0] + ans[1] == number)
        and is_prime(ans[0] )
        and is_prime(ans[1] )
    ), "'ans' must contains two primes. And sum of elements must been eq 'number'"

    return ans

def      _lowerCamelCase	(						__A    :							str		,		__A    :							Optional[int] )      ->					Optional[Any]:
    assert (
        isinstance(__A		,		__A )
        and isinstance(__A		,		__A )
        and (numbera >= 0)
        and (numbera >= 0)
    ), "'number1' and 'number2' must been positive integer."

    _UpperCAmelCase				:      Dict			  =				0

    while numbera != 0:
        _UpperCAmelCase				:      Optional[int]			  =				numbera % numbera
        _UpperCAmelCase				:      Tuple			  =				numbera
        _UpperCAmelCase				:      List[str]			  =				rest

    # precondition
    assert isinstance(__A		,		__A ) and (
        numbera >= 0
    ), "'number' must been from type int and positive"

    return numbera

def      _lowerCamelCase	(						__A    :							Dict		,		__A    :							List[str] )      ->					Optional[int]:
    assert (
        isinstance(__A		,		__A )
        and isinstance(__A		,		__A )
        and (numbera >= 1)
        and (numbera >= 1)
    ), "'number1' and 'number2' must been positive integer."

    _UpperCAmelCase				:      Optional[Any]			  =				1  # actual answer that will be return.

    # for kgV (x,1)
    if numbera > 1 and numbera > 1:
        # builds the prime factorization of 'number1' and 'number2'
        _UpperCAmelCase				:      int			  =				prime_factorization(__A )
        _UpperCAmelCase				:      List[str]			  =				prime_factorization(__A )

    elif numbera == 1 or numbera == 1:
        _UpperCAmelCase				:      Any			  =				[]
        _UpperCAmelCase				:      Any			  =				[]
        _UpperCAmelCase				:      Any			  =				max(__A		,		__A )

    _UpperCAmelCase				:      List[Any]			  =				0
    _UpperCAmelCase				:      Tuple			  =				0

    _UpperCAmelCase				:      List[str]			  =				[]  # captured numbers int both 'primeFac1' and 'primeFac2'

    # iterates through primeFac1
    for n in prime_fac_a:
        if n not in done:
            if n in prime_fac_a:
                _UpperCAmelCase				:      str			  =				prime_fac_a.count(__A )
                _UpperCAmelCase				:      Optional[int]			  =				prime_fac_a.count(__A )

                for _ in range(max(__A		,		__A ) ):
                    ans *= n

            else:
                _UpperCAmelCase				:      int			  =				prime_fac_a.count(__A )

                for _ in range(__A ):
                    ans *= n

            done.append(__A )

    # iterates through primeFac2
    for n in prime_fac_a:
        if n not in done:
            _UpperCAmelCase				:      List[Any]			  =				prime_fac_a.count(__A )

            for _ in range(__A ):
                ans *= n

            done.append(__A )

    # precondition
    assert isinstance(__A		,		__A ) and (
        ans >= 0
    ), "'ans' must been from type int and positive"

    return ans

def      _lowerCamelCase	(						__A    :							Optional[int] )      ->					Optional[int]:
    assert isinstance(__A		,		__A ) and (n >= 0), "'number' must been a positive int"

    _UpperCAmelCase				:      Union[str, Any]			  =				0
    _UpperCAmelCase				:      str			  =				2  # this variable holds the answer

    while index < n:
        index += 1

        ans += 1  # counts to the next number

        # if ans not prime then
        # runs to the next prime number.
        while not is_prime(__A ):
            ans += 1

    # precondition
    assert isinstance(__A		,		__A ) and is_prime(
        __A ), "'ans' must been a prime number and from type int"

    return ans

def      _lowerCamelCase	(						__A    :							List[Any]		,		__A    :							List[Any] )      ->					Any:
    assert (
        is_prime(__A ) and is_prime(__A ) and (p_number_a < p_number_a)
    ), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"

    _UpperCAmelCase				:      List[str]			  =				p_number_a + 1  # jump to the next number

    _UpperCAmelCase				:      List[str]			  =				[]  # this list will be returns.

    # if number is not prime then
    # fetch the next prime number.
    while not is_prime(__A ):
        number += 1

    while number < p_number_a:
        ans.append(__A )

        number += 1

        # fetch the next prime number.
        while not is_prime(__A ):
            number += 1

    # precondition
    assert (
        isinstance(__A		,		__A )
        and ans[0] != p_number_a
        and ans[len(__A ) - 1] != p_number_a
    ), "'ans' must been a list without the arguments"

    # 'ans' contains not 'pNumber1' and 'pNumber2' !
    return ans

def      _lowerCamelCase	(						__A    :							Optional[Any] )      ->					int:
    assert isinstance(__A		,		__A ) and (n >= 1), "'n' must been int and >= 1"

    _UpperCAmelCase				:      int			  =				[]  # will be returned.

    for divisor in range(1		,		n + 1 ):
        if n % divisor == 0:
            ans.append(__A )

    # precondition
    assert ans[0] == 1 and ans[len(__A ) - 1] == n, "Error in function getDivisiors(...)"

    return ans

def      _lowerCamelCase	(						__A    :							str )      ->					int:
    assert isinstance(__A		,		__A ) and (
        number > 1
    ), "'number' must been an int and >= 1"

    _UpperCAmelCase				:      List[str]			  =				get_divisors(__A )

    # precondition
    assert (
        isinstance(__A		,		__A )
        and (divisors[0] == 1)
        and (divisors[len(__A ) - 1] == number)
    ), "Error in help-function getDivisiors(...)"

    # summed all divisors up to 'number' (exclusive), hence [:-1]
    return sum(divisors[:-1] ) == number

def      _lowerCamelCase	(						__A    :							int		,		__A    :							Any )      ->					List[Any]:
    assert (
        isinstance(__A		,		__A )
        and isinstance(__A		,		__A )
        and (denominator != 0)
    ), "The arguments must been from type int and 'denominator' != 0"

    # build the greatest common divisor of numerator and denominator.
    _UpperCAmelCase				:      Tuple			  =				gcd(abs(__A )		,		abs(__A ) )

    # precondition
    assert (
        isinstance(__A		,		__A )
        and (numerator % gcd_of_fraction == 0)
        and (denominator % gcd_of_fraction == 0)
    ), "Error in function gcd(...,...)"

    return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)

def      _lowerCamelCase	(						__A    :							int )      ->					str:
    assert isinstance(__A		,		__A ) and (n >= 0), "'n' must been a int and >= 0"

    _UpperCAmelCase				:      int			  =				1  # this will be return.

    for factor in range(1		,		n + 1 ):
        ans *= factor

    return ans


def      _lowerCamelCase	(						__A    :							List[Any] )      ->					str:
    assert isinstance(__A		,		__A ) and (n >= 0), "'n' must been an int and >= 0"

    _UpperCAmelCase				:      str			  =				0
    _UpperCAmelCase				:      List[Any]			  =				1
    _UpperCAmelCase				:      Dict			  =				1  # this will be return

    for _ in range(n - 1 ):
        _UpperCAmelCase				:      List[str]			  =				ans
        ans += fiba
        _UpperCAmelCase				:      Optional[int]			  =				tmp

    return ans












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_    (						__lowercase ,   __lowercase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Dict =					StableDiffusionXLImgaImgPipeline
 _SCREAMING_SNAKE_CASE							:			Any =					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
 _SCREAMING_SNAKE_CASE							:			List[Any] =					PipelineTesterMixin.required_optional_params - {"latents"}
 _SCREAMING_SNAKE_CASE							:			Dict =					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
 _SCREAMING_SNAKE_CASE							:			List[Any] =					IMAGE_TO_IMAGE_IMAGE_PARAMS
 _SCREAMING_SNAKE_CASE							:			Dict =					IMAGE_TO_IMAGE_IMAGE_PARAMS


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     torch.manual_seed(0)
     _UpperCAmelCase				:      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''')							,  attention_head_dim=(2, 4)							,  use_linear_projection=_A							,  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							,  )
     _UpperCAmelCase				:      int			  =				EulerDiscreteScheduler(
         beta_start=0.00085							,  beta_end=0.012							,  steps_offset=1							,  beta_schedule='''scaled_linear'''							,  timestep_spacing='''leading'''							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      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							,  sample_size=128							,  )
     torch.manual_seed(0)
     _UpperCAmelCase				:      Tuple			  =				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=1000							,  hidden_act='''gelu'''							,  projection_dim=32							,  )
     _UpperCAmelCase				:      int			  =				CLIPTextModel(_A)
     _UpperCAmelCase				:      Tuple			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      int			  =				CLIPTextModelWithProjection(_A)
     _UpperCAmelCase				:      Optional[int]			  =				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''							,  local_files_only=_A)

     _UpperCAmelCase				:      Any			  =				{
         '''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  snake_case__				(	self							,  _A							,  _A=0) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				floats_tensor((1, 3, 32, 32)							,  rng=random.Random(_A)).to(_A)
     _UpperCAmelCase				:      List[Any]			  =				image / 2 + 0.5
     if str(_A).startswith('''mps'''):
         _UpperCAmelCase				:      Union[str, Any]			  =				torch.manual_seed(_A)
     else:
         _UpperCAmelCase				:      List[str]			  =				torch.Generator(device=_A).manual_seed(_A)
     _UpperCAmelCase				:      Tuple			  =				{
         '''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.75,
     }
     return inputs


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

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      Any			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      List[str]			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      Tuple			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe(**_A).images
     _UpperCAmelCase				:      Any			  =				image[0, -3:, -3:, -1]

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

     _UpperCAmelCase				:      Optional[Any]			  =				np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165])

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


 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)


 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



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


 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     pass


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.get_dummy_components()
     _UpperCAmelCase				:      str			  =				StableDiffusionXLImgaImgPipeline(**_A)
     _UpperCAmelCase				:      Any			  =				sd_pipe.to(_A)
     _UpperCAmelCase				:      Tuple			  =				sd_pipe.to(_A)
     sd_pipe.set_progress_bar_config(disable=_A)

     # forward without prompt embeds
     _UpperCAmelCase				:      str			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Optional[int]			  =				negative_prompt
     _UpperCAmelCase				:      Optional[int]			  =				3 * [inputs['''prompt''']]

     _UpperCAmelCase				:      Optional[Any]			  =				sd_pipe(**_A)
     _UpperCAmelCase				:      Any			  =				output.images[0, -3:, -3:, -1]

     # forward with prompt embeds
     _UpperCAmelCase				:      Dict			  =				self.get_dummy_inputs(_A)
     _UpperCAmelCase				:      Optional[Any]			  =				3 * ['''this is a negative prompt''']
     _UpperCAmelCase				:      Dict			  =				3 * [inputs.pop('''prompt''')]

     (
         (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , (
         _UpperCAmelCase
     )  , 
     )				:      str			  =				sd_pipe.encode_prompt(_A							,  negative_prompt=_A)

     _UpperCAmelCase				:      str			  =				sd_pipe(
         **_A							,  prompt_embeds=_A							,  negative_prompt_embeds=_A							,  pooled_prompt_embeds=_A							,  negative_pooled_prompt_embeds=_A							,  )
     _UpperCAmelCase				:      List[str]			  =				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			):






 '''simple docstring'''




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

     """simple docstring"""



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


 def  snake_case__				(	self							,  _A							,  _A="cpu"							,  _A=torch.floataa							,  _A=0) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				torch.Generator(device=_A).manual_seed(_A)
     _UpperCAmelCase				:      Any			  =				np.random.RandomState(_A).standard_normal((1, 4, 64, 64))
     _UpperCAmelCase				:      Dict			  =				torch.from_numpy(_A).to(device=_A							,  dtype=_A)
     _UpperCAmelCase				:      str			  =				{
         '''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  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				DiffusionPipeline.from_pretrained('''stabilityai/stable-diffusion-2-base''')
     pipe.to(_A)
     pipe.set_progress_bar_config(disable=_A)

     _UpperCAmelCase				:      str			  =				self.get_inputs(_A)
     _UpperCAmelCase				:      Union[str, Any]			  =				pipe(**_A).images
     _UpperCAmelCase				:      Optional[int]			  =				image[0, -3:, -3:, -1].flatten()

     assert image.shape == (1, 512, 512, 3)
     _UpperCAmelCase				:      int			  =				np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])
     assert np.abs(image_slice - expected_slice).max() < 7e-3




