'''simple docstring'''

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    lowerCamelCase__  (   __snake_case       ,				unittest.TestCase     ):
   __UpperCAmelCase           =						KandinskyVaaPriorEmbaEmbPipeline
   __UpperCAmelCase           =						["""prompt""", """image"""]
   __UpperCAmelCase           =						["""prompt""", """image"""]
   __UpperCAmelCase           =						[
       """num_images_per_prompt""",
       """strength""",
       """generator""",
       """num_inference_steps""",
       """latents""",
       """negative_prompt""",
       """guidance_scale""",
       """output_type""",
       """return_dict""",
   ]
   __UpperCAmelCase           =						False



   @property
   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        return 32



   @property
   def  _UpperCamelCase		(    self     )				->     Dict:
        """simple docstring"""





        return 32



   @property
   def  _UpperCamelCase		(    self     )				->     Any:
        """simple docstring"""





        return self.time_input_dim



   @property
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        return self.time_input_dim * 4



   @property
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        return 100



   @property
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase  :str       =CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""     )
        return tokenizer



   @property
   def  _UpperCamelCase		(    self     )				->     Optional[Any]:
        """simple docstring"""





        torch.manual_seed(0     )
        _UpperCamelCase  :List[str]       =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=1_000					,      )
        return CLIPTextModelWithProjection(lowerCAmelCase__     )



   @property
   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        torch.manual_seed(0     )

        _UpperCamelCase  :Optional[int]       ={
            """num_attention_heads""": 2,
            """attention_head_dim""": 12,
            """embedding_dim""": self.text_embedder_hidden_size,
            """num_layers""": 1,
        }

        _UpperCamelCase  :List[str]       =PriorTransformer(**lowerCAmelCase__     )
        # 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
        _UpperCamelCase  :Dict       =nn.Parameter(torch.ones(model.clip_std.shape     )     )
        return model



   @property
   def  _UpperCamelCase		(    self     )				->     List[str]:
        """simple docstring"""





        torch.manual_seed(0     )
        _UpperCamelCase  :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					,      )

        _UpperCamelCase  :Union[str, Any]       =CLIPVisionModelWithProjection(lowerCAmelCase__     )
        return model



   @property
   def  _UpperCamelCase		(    self     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase  :List[Any]       =CLIPImageProcessor(
            crop_size=224					,      do_center_crop=lowerCAmelCase__					,      do_normalize=lowerCAmelCase__					,      do_resize=lowerCAmelCase__					,      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     )				->     int:
        """simple docstring"""





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

        _UpperCamelCase  :Dict       =UnCLIPScheduler(
            variance_type="""fixed_small_log"""					,      prediction_type="""sample"""					,      num_train_timesteps=1_000					,      clip_sample=lowerCAmelCase__					,      clip_sample_range=10.0					,      )

        _UpperCamelCase  :int       ={
            """prior""": prior,
            """image_encoder""": image_encoder,
            """text_encoder""": text_encoder,
            """tokenizer""": tokenizer,
            """scheduler""": scheduler,
            """image_processor""": image_processor,
        }

        return components



   def  _UpperCamelCase		(    self					,      lowerCAmelCase__					,      lowerCAmelCase__=0     )				->     Optional[Any]:
        """simple docstring"""





        if str(lowerCAmelCase__     ).startswith("""mps"""     ):
             _UpperCamelCase  :List[Any]       =torch.manual_seed(lowerCAmelCase__     )
        else:
             _UpperCamelCase  :Optional[int]       =torch.Generator(device=lowerCAmelCase__     ).manual_seed(lowerCAmelCase__     )

        _UpperCamelCase  :Optional[Any]       =floats_tensor((1, 3, 64, 64)					,      rng=random.Random(lowerCAmelCase__     )     ).to(lowerCAmelCase__     )
        _UpperCamelCase  :Optional[Any]       =image.cpu().permute(0					,      2					,      3					,      1     )[0]
        _UpperCamelCase  :Dict       =Image.fromarray(np.uinta(lowerCAmelCase__     )     ).convert("""RGB"""     ).resize((256, 256)     )

        _UpperCamelCase  :Tuple       ={
            """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     )				->     Any:
        """simple docstring"""





        _UpperCamelCase  :Optional[Any]       ="""cpu"""

        _UpperCamelCase  :List[Any]       =self.get_dummy_components()

        _UpperCamelCase  :int       =self.pipeline_class(**lowerCAmelCase__     )
        _UpperCamelCase  :Dict       =pipe.to(lowerCAmelCase__     )

        pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

        _UpperCamelCase  :Union[str, Any]       =pipe(**self.get_dummy_inputs(lowerCAmelCase__     )     )
        _UpperCamelCase  :Any       =output.image_embeds

        _UpperCamelCase  :Optional[Any]       =pipe(
            **self.get_dummy_inputs(lowerCAmelCase__     )					,      return_dict=lowerCAmelCase__					,      )[0]

        _UpperCamelCase  :int       =image[0, -10:]
        _UpperCamelCase  :Optional[int]       =image_from_tuple[0, -10:]

        assert image.shape == (1, 32)

        _UpperCamelCase  :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     )				->     List[Any]:
        """simple docstring"""





        _UpperCamelCase  :Dict       =torch_device == """cpu"""
        _UpperCamelCase  :List[Any]       =True
        _UpperCamelCase  :Dict       =False

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




   @skip_mps
   def  _UpperCamelCase		(    self     )				->     Optional[int]:
        """simple docstring"""





        _UpperCamelCase  :Tuple       =torch_device == """cpu"""
        _UpperCamelCase  :Union[str, Any]       =False

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


from __future__ import annotations



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  assert n > 1 and a > 0 and greatest_common_divisor(_UpperCamelCase					,			_UpperCamelCase	) == 1
  ((_snake_case),	(_snake_case),	(_snake_case))		=				extended_gcd(_UpperCamelCase					,			_UpperCamelCase	)  # Implemented below
  _snake_case		=				(b * s) % n
  return x



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  ((_snake_case),	(_snake_case))		=				extended_euclid(_UpperCamelCase					,			_UpperCamelCase	)  # Implemented below
  if b < 0:
    _snake_case		=				(b % n + n) % n
  return b



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  _snake_case		=				invert_modulo(_UpperCamelCase					,			_UpperCamelCase	)
  _snake_case		=				(b * s) % n
  return x



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      tuple[int, int, int]:



  """simple docstring"""






  assert a >= 0 and b >= 0

  if b == 0:
    _snake_case,	_snake_case,	_snake_case		=				a, 1, 0
  else:
    ((_snake_case),	(_snake_case),	(_snake_case))		=				extended_gcd(_UpperCamelCase					,			a % b	)
    _snake_case		=				q
    _snake_case		=				p - q * (a // b)

  assert a % d == 0 and b % d == 0
  assert d == a * x + b * y

  return (d, x, y)



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      tuple[int, int]:



  """simple docstring"""






  if b == 0:
    return (1, 0)
  ((_snake_case),	(_snake_case))		=				extended_euclid(_UpperCamelCase					,			a % b	)
  _snake_case		=				a // b
  return (y, x - k * y)



def  snake_case_(_UpperCamelCase					,			_UpperCamelCase	)				->      int:



  """simple docstring"""






  if a < b:
    _snake_case,	_snake_case		=				b, a

  while a % b != 0:
    _snake_case,	_snake_case		=				b, a % b

  return b


if __name__ == "__main__":
 from doctest import testmod

 testmod(name='''modular_division''', verbose=True)
 testmod(name='''modular_division2''', verbose=True)
 testmod(name='''invert_modulo''', verbose=True)
 testmod(name='''extended_gcd''', verbose=True)
 testmod(name='''extended_euclid''', verbose=True)
 testmod(name='''greatest_common_divisor''', verbose=True)

