





"""simple docstring"""
import unittest

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

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

from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()
class lowerCamelCase__	(     UpperCamelCase_	,					unittest.TestCase					):
   __UpperCAmelCase										=       KandinskyVaaPriorPipeline
   __UpperCAmelCase										=       ['prompt']
   __UpperCAmelCase										=       ['prompt', 'negative_prompt']
   __UpperCAmelCase										=       [
       'num_images_per_prompt',
       'generator',
       'num_inference_steps',
       'latents',
       'negative_prompt',
       'guidance_scale',
       'output_type',
       'return_dict',
   ]
   __UpperCAmelCase										=       False



   @property
   def  _UpperCAmelCase						(							self						)			->     Optional[int]:







      """simple docstring"""
      return 3_2



   @property
   def  _UpperCAmelCase						(							self						)			->     List[str]:







      """simple docstring"""
      return 3_2



   @property
   def  _UpperCAmelCase						(							self						)			->     int:







      """simple docstring"""
      return self.time_input_dim



   @property
   def  _UpperCAmelCase						(							self						)			->     Tuple:







      """simple docstring"""
      return self.time_input_dim * 4



   @property
   def  _UpperCAmelCase						(							self						)			->     Dict:







      """simple docstring"""
      return 1_0_0



   @property
   def  _UpperCAmelCase						(							self						)			->     Union[str, Any]:







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



   @property
   def  _UpperCAmelCase						(							self						)			->     List[str]:







      """simple docstring"""
      torch.manual_seed(0						)
      lowercase     :      int	=							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=3_7   , layer_norm_eps=1E-05   , num_attention_heads=4   , num_hidden_layers=5   , pad_token_id=1   , vocab_size=1_0_0_0   , )
      return CLIPTextModelWithProjection(lowercase_						)



   @property
   def  _UpperCAmelCase						(							self						)			->     Optional[Any]:







      """simple docstring"""
      torch.manual_seed(0						)

      lowercase     :      Any	=							{
          'num_attention_heads': 2,
          'attention_head_dim': 1_2,
          'embedding_dim': self.text_embedder_hidden_size,
          'num_layers': 1,
      }

      lowercase     :      Dict	=							PriorTransformer(**lowercase_						)
      # 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
      lowercase     :      Optional[Any]	=							nn.Parameter(torch.ones(model.clip_std.shape						)						)
      return model



   @property
   def  _UpperCAmelCase						(							self						)			->     List[Any]:







      """simple docstring"""
      torch.manual_seed(0						)
      lowercase     :      str	=							CLIPVisionConfig(
          hidden_size=self.text_embedder_hidden_size   , image_size=2_2_4   , projection_dim=self.text_embedder_hidden_size   , intermediate_size=3_7   , num_attention_heads=4   , num_channels=3   , num_hidden_layers=5   , patch_size=1_4   , )

      lowercase     :      int	=							CLIPVisionModelWithProjection(lowercase_						)
      return model



   @property
   def  _UpperCAmelCase						(							self						)			->     Dict:







      """simple docstring"""
      lowercase     :      Dict	=							CLIPImageProcessor(
          crop_size=2_2_4   , do_center_crop=lowercase_   , do_normalize=lowercase_   , do_resize=lowercase_   , image_mean=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73]   , image_std=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11]   , resample=3   , size=2_2_4   , )

      return image_processor



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







      """simple docstring"""
      lowercase     :      List[str]	=							self.dummy_prior
      lowercase     :      List[str]	=							self.dummy_image_encoder
      lowercase     :      List[Any]	=							self.dummy_text_encoder
      lowercase     :      List[str]	=							self.dummy_tokenizer
      lowercase     :      List[str]	=							self.dummy_image_processor

      lowercase     :      Dict	=							UnCLIPScheduler(
          variance_type="""fixed_small_log"""   , prediction_type="""sample"""   , num_train_timesteps=1_0_0_0   , clip_sample=lowercase_   , clip_sample_range=10.0   , )

      lowercase     :      Optional[Any]	=							{
          'prior': prior,
          'image_encoder': image_encoder,
          'text_encoder': text_encoder,
          'tokenizer': tokenizer,
          'scheduler': scheduler,
          'image_processor': image_processor,
      }

      return components



   def  _UpperCAmelCase						(							self   , snake_case   , snake_case=0						)			->     Union[str, Any]:







      """simple docstring"""




      if str(lowercase_						).startswith("""mps"""						):
         lowercase     :      Any	=							torch.manual_seed(lowercase_						)
      else:
         lowercase     :      List[str]	=							torch.Generator(device=lowercase_						).manual_seed(lowercase_						)
      lowercase     :      Dict	=							{
          'prompt': 'horse',
          'generator': generator,
          'guidance_scale': 4.0,
          'num_inference_steps': 2,
          'output_type': 'np',
      }
      return inputs



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







      """simple docstring"""
      lowercase     :      List[Any]	=							'cpu'

      lowercase     :      Any	=							self.get_dummy_components()

      lowercase     :      str	=							self.pipeline_class(**lowercase_						)
      lowercase     :      int	=							pipe.to(lowercase_						)

      pipe.set_progress_bar_config(disable=lowercase_						)

      lowercase     :      Dict	=							pipe(**self.get_dummy_inputs(lowercase_						)						)
      lowercase     :      Dict	=							output.image_embeds

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

      lowercase     :      Tuple	=							image[0, -1_0:]
      lowercase     :      Union[str, Any]	=							image_from_tuple[0, -1_0:]

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

      lowercase     :      int	=							np.array(
          [-0.05_32, 1.71_20, 0.36_56, -1.08_52, -0.89_46, -1.17_56, 0.43_48, 0.24_82, 0.51_46, -0.11_56]						)

      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						)			->     Union[str, Any]:







      """simple docstring"""
      lowercase     :      Any	=							torch_device == 'cpu'
      lowercase     :      Dict	=							True
      lowercase     :      Dict	=							False

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





   @skip_mps
   def  _UpperCAmelCase						(							self						)			->     int:







      """simple docstring"""
      lowercase     :      Optional[int]	=							torch_device == 'cpu'
      lowercase     :      int	=							False

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






from timeit import timeit

lowerCamelCase		   =			{
    'MALAYALAM': True,
    'String': False,
    'rotor': True,
    'level': True,
    'A': True,
    'BB': True,
    'ABC': False,
    'amanaplanacanalpanama': True,  # "a man a plan a canal panama"
}
# Ensure our test data is valid
assert all((key == key[::-1]) is value for key, value in test_data.items())




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =0
       _lowerCamelCase			:						Union[str, Any]            =len(SCREAMING_SNAKE_CASE__	) - 1
       while start_i < end_i:
              if s[start_i] == s[end_i]:
                     start_i += 1
                     end_i -= 1
              else:
                     return False
       return True




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						List[str]            =len(SCREAMING_SNAKE_CASE__	) // 2
       _lowerCamelCase			:						Optional[Any]            =len(SCREAMING_SNAKE_CASE__	)

       # We need to traverse till half of the length of string
       # as we can get access of the i'th last element from
       # i'th index.
       # eg: [0,1,2,3,4,5] => 4th index can be accessed
       # with the help of 1st index (i==n-i-1)
       # where n is length of string
       return all(s[i] == s[n - i - 1] for i in range(SCREAMING_SNAKE_CASE__	)	)




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       if len(SCREAMING_SNAKE_CASE__	) <= 2:
              return True
       if s[0] == s[len(SCREAMING_SNAKE_CASE__	) - 1]:
              return is_palindrome_recursive(s[1:-1]	)
       else:
              return False




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       return s == s[::-1]




def       a_ (       SCREAMING_SNAKE_CASE__   : str	):
       '''simple docstring'''





       _lowerCamelCase			:						Optional[int]            =F'''all({name}(key) is value for key, value in test_data.items())'''
       _lowerCamelCase			:						List[Any]            =F'''from __main__ import test_data, {name}'''
       _lowerCamelCase			:						Any            =500_000
       _lowerCamelCase			:						Dict            =timeit(stmt=SCREAMING_SNAKE_CASE__						,     setup=SCREAMING_SNAKE_CASE__						,     number=SCREAMING_SNAKE_CASE__	)
       print(F'''{name:<35} finished {number:,} runs in {result:.5f} seconds'''	)


if __name__ == "__main__":
 for key, value in test_data.items():
  assert is_palindrome(key) is is_palindrome_recursive(key)
  assert is_palindrome(key) is is_palindrome_slice(key)
  print(F"""{key:21} {value}""")
 print('a man a plan a canal panama')

 # finished 500,000 runs in 0.46793 seconds
 benchmark_function('is_palindrome_slice')
 # finished 500,000 runs in 0.85234 seconds
 benchmark_function('is_palindrome')
 # finished 500,000 runs in 1.32028 seconds
 benchmark_function('is_palindrome_recursive')
 # finished 500,000 runs in 2.08679 seconds
 benchmark_function('is_palindrome_traversal')


