

import random
import unittest

import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers import (
    CLIPImageProcessor,
    CLIPTextConfig,
    CLIPTextModelWithProjection,
    CLIPTokenizer,
    CLIPVisionConfig,
    CLIPVisionModelWithProjection,
)

from diffusers import KandinskyVaaPriorEmbaEmbPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 			SCREAMING_SNAKE_CASE					(							lowercase_      ,unittest.TestCase					):






      '''simple docstring'''






      SCREAMING_SNAKE_CASE__ :				Any    =				KandinskyVaaPriorEmbaEmbPipeline
      SCREAMING_SNAKE_CASE__ :				List[str]    =				['''prompt''', '''image''']
      SCREAMING_SNAKE_CASE__ :				Optional[int]    =				['''prompt''', '''image''']
      SCREAMING_SNAKE_CASE__ :				Optional[Any]    =				[
          '''num_images_per_prompt''',
          '''strength''',
          '''generator''',
          '''num_inference_steps''',
          '''latents''',
          '''negative_prompt''',
          '''guidance_scale''',
          '''output_type''',
          '''return_dict''',
      ]
      SCREAMING_SNAKE_CASE__ :				Dict    =				False




      @property
      def 	__UpperCAmelCase			(					self :		List[str]   ):



          """simple docstring"""





          return 32




      @property
      def 	__UpperCAmelCase			(					self :		Union[str, Any]   ):



          """simple docstring"""





          return 32




      @property
      def 	__UpperCAmelCase			(					self :		Dict   ):



          """simple docstring"""





          return self.time_input_dim




      @property
      def 	__UpperCAmelCase			(					self :		int   ):



          """simple docstring"""





          return self.time_input_dim * 4




      @property
      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          return 100




      @property
      def 	__UpperCAmelCase			(					self :		Optional[int]   ):



          """simple docstring"""





          _snake_case : Optional[Any]												=		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )
          return tokenizer




      @property
      def 	__UpperCAmelCase			(					self :		List[str]   ):



          """simple docstring"""





          torch.manual_seed(0   )
          _snake_case : List[Any]												=		CLIPTextConfig(
              bos_token_id=0     ,					eos_token_id=2     ,					hidden_size=self.text_embedder_hidden_size     ,					projection_dim=self.text_embedder_hidden_size     ,					intermediate_size=37     ,					layer_norm_eps=1e-05     ,					num_attention_heads=4     ,					num_hidden_layers=5     ,					pad_token_id=1     ,					vocab_size=1000     ,					)
          return CLIPTextModelWithProjection(snake_case   )




      @property
      def 	__UpperCAmelCase			(					self :		Union[str, Any]   ):



          """simple docstring"""





          torch.manual_seed(0   )

          _snake_case : List[str]												=		{
              'num_attention_heads': 2,
              'attention_head_dim': 12,
              'embedding_dim': self.text_embedder_hidden_size,
              'num_layers': 1,
          }

          _snake_case : str												=		PriorTransformer(**snake_case   )
          # clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
          _snake_case : Optional[int]												=		nn.Parameter(torch.ones(model.clip_std.shape   )   )
          return model




      @property
      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          torch.manual_seed(0   )
          _snake_case : List[Any]												=		CLIPVisionConfig(
              hidden_size=self.text_embedder_hidden_size     ,					image_size=224     ,					projection_dim=self.text_embedder_hidden_size     ,					intermediate_size=37     ,					num_attention_heads=4     ,					num_channels=3     ,					num_hidden_layers=5     ,					patch_size=14     ,					)

          _snake_case : Any												=		CLIPVisionModelWithProjection(snake_case   )
          return model




      @property
      def 	__UpperCAmelCase			(					self :		Any   ):



          """simple docstring"""





          _snake_case : Any												=		CLIPImageProcessor(
              crop_size=224     ,					do_center_crop=snake_case     ,					do_normalize=snake_case     ,					do_resize=snake_case     ,					image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073]     ,					image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711]     ,					resample=3     ,					size=224     ,					)

          return image_processor




      def 	__UpperCAmelCase			(					self :		str   ):



          """simple docstring"""





          _snake_case : str												=		self.dummy_prior
          _snake_case : Optional[int]												=		self.dummy_image_encoder
          _snake_case : List[Any]												=		self.dummy_text_encoder
          _snake_case : Tuple												=		self.dummy_tokenizer
          _snake_case : List[Any]												=		self.dummy_image_processor

          _snake_case : Any												=		UnCLIPScheduler(
              variance_type='fixed_small_log'     ,					prediction_type='sample'     ,					num_train_timesteps=1000     ,					clip_sample=snake_case     ,					clip_sample_range=10.0     ,					)

          _snake_case : Optional[int]												=		{
              'prior': prior,
              'image_encoder': image_encoder,
              'text_encoder': text_encoder,
              'tokenizer': tokenizer,
              'scheduler': scheduler,
              'image_processor': image_processor,
          }

          return components




      def 	__UpperCAmelCase			(					self :		List[Any]     ,					snake_case :		List[Any]     ,					snake_case :		Dict=0   ):



          """simple docstring"""





          if str(snake_case   ).startswith('mps'   ):
              _snake_case : str												=		torch.manual_seed(snake_case   )
          else:
              _snake_case : str												=		torch.Generator(device=snake_case   ).manual_seed(snake_case   )

          _snake_case : Optional[Any]												=		floats_tensor((1, 3, 64, 64)     ,					rng=random.Random(snake_case   )   ).to(snake_case   )
          _snake_case : Tuple												=		image.cpu().permute(0     ,					2     ,					3     ,					1   )[0]
          _snake_case : Optional[int]												=		Image.fromarray(np.uinta(snake_case   )   ).convert('RGB'   ).resize((256, 256)   )

          _snake_case : Optional[Any]												=		{
              'prompt': 'horse',
              'image': init_image,
              'strength': 0.5,
              'generator': generator,
              'guidance_scale': 4.0,
              'num_inference_steps': 2,
              'output_type': 'np',
          }
          return inputs




      def 	__UpperCAmelCase			(					self :		List[Any]   ):



          """simple docstring"""





          _snake_case : List[str]												=		'cpu'

          _snake_case : int												=		self.get_dummy_components()

          _snake_case : List[str]												=		self.pipeline_class(**snake_case   )
          _snake_case : str												=		pipe.to(snake_case   )

          pipe.set_progress_bar_config(disable=snake_case   )

          _snake_case : Dict												=		pipe(**self.get_dummy_inputs(snake_case   )   )
          _snake_case : Any												=		output.image_embeds

          _snake_case : List[str]												=		pipe(
              **self.get_dummy_inputs(snake_case   )     ,					return_dict=snake_case     ,					)[0]

          _snake_case : Tuple												=		image[0, -10:]
          _snake_case : str												=		image_from_tuple[0, -10:]

          assert image.shape == (1, 32)

          _snake_case : Optional[int]												=		np.array(
              [
                  0.107_1284,
                  1.333_0271,
                  0.6126_0223,
                  -0.669_1065,
                  -0.384_6852,
                  -1.030_3661,
                  0.2271_6111,
                  0.0334_8901,
                  0.3004_0675,
                  -0.2480_5029,
              ]   )

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




      @skip_mps
      def 	__UpperCAmelCase			(					self :		Dict   ):



          """simple docstring"""





          _snake_case : str												=		torch_device == 'cpu'
          _snake_case : str												=		True
          _snake_case : str												=		False

          self._test_inference_batch_single_identical(
              test_max_difference=snake_case     ,					relax_max_difference=snake_case     ,					test_mean_pixel_difference=snake_case     ,					)




      @skip_mps
      def 	__UpperCAmelCase			(					self :		Dict   ):



          """simple docstring"""





          _snake_case : List[str]												=		torch_device == 'cpu'
          _snake_case : int												=		False

          self._test_attention_slicing_forward_pass(
              test_max_difference=snake_case     ,					test_mean_pixel_difference=snake_case     ,					)






'''simple docstring'''



from __future__ import annotations

from collections import Counter

def   lowerCamelCase__       (      a__)		->    list[int]:



    """simple docstring"""







    _snake_case : Optional[int]												=		[True] * n
    _snake_case : List[str]												=		False
    _snake_case : int												=		False
    _snake_case : Tuple												=		True

    for i in range(3			,      int(n**0.5 + 1)			,      2):
        _snake_case : int												=		i * 2
        while index < n:
            _snake_case : List[str]												=		False
            _snake_case : Union[str, Any]												=		index + i

    _snake_case : List[str]												=		[2]

    for i in range(3			,      a__			,      2):
        if is_prime[i]:
            primes.append(a__)

    return primes

def   lowerCamelCase__       (      a__)		->    list[list[int]]:



    """simple docstring"""







    _snake_case : Tuple												=		str(a__)
    _snake_case : str												=		[]
    _snake_case : Union[str, Any]												=		['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

    for duplicate in Counter(a__) - Counter(set(a__)):
        _snake_case : List[Any]												=		[int(number_str.replace(a__			,      a__)) for digit in digits]
        replacements.append(a__)

    return replacements

def   lowerCamelCase__       (      a__ = 8)		->    int:



    """simple docstring"""







    _snake_case : Any												=		set()

    # Filter primes with less than 3 replaceable digits
    _snake_case : List[Any]												=		{
        x for x in set(prime_sieve(1_0_0_0_0_0_0)) if len(str(a__)) - len(set(str(a__))) >= 3
    }

    for prime in primes:
        if prime in numbers_checked:
            continue

        _snake_case : int												=		digit_replacements(a__)

        for family in replacements:
            numbers_checked.update(a__)
            _snake_case : Union[str, Any]												=		primes.intersection(a__)

            if len(a__) != family_length:
                continue

            return min(a__)

    return -1


if __name__ == "__main__":
   print(solution())



