



"""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       UpperCamelCase__   (	A__,					unittest.TestCase  ):




      """simple docstring"""




      _SCREAMING_SNAKE_CASE  				=     KandinskyVaaPriorPipeline
      _SCREAMING_SNAKE_CASE  				=     ["""prompt"""]
      _SCREAMING_SNAKE_CASE  				=     ["""prompt""", """negative_prompt"""]
      _SCREAMING_SNAKE_CASE  				=     [
          """num_images_per_prompt""",
          """generator""",
          """num_inference_steps""",
          """latents""",
          """negative_prompt""",
          """guidance_scale""",
          """output_type""",
          """return_dict""",
      ]
      _SCREAMING_SNAKE_CASE  				=     False



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        return 3_2



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        return 3_2



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        return self.time_input_dim



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Dict       ):
        return self.time_input_dim * 4



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[Any]       ):
        return 1_0_0



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      int       ):
        lowerCAmelCase_   :				List[str]								= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'       )
        return tokenizer



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      List[str]       ):
        torch.manual_seed(0       )
        lowerCAmelCase_   :				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=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(_A       )



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[Any]       ):
        torch.manual_seed(0       )

        lowerCAmelCase_   :				Tuple								= {
            "num_attention_heads": 2,
            "attention_head_dim": 1_2,
            "embedding_dim": self.text_embedder_hidden_size,
            "num_layers": 1,
        }

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



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        torch.manual_seed(0       )
        lowerCAmelCase_   :				Tuple								= 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    ,			)

        lowerCAmelCase_   :				Optional[Any]								= CLIPVisionModelWithProjection(_A       )
        return model



      @property
      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        lowerCAmelCase_   :				List[Any]								= CLIPImageProcessor(
            crop_size=2_2_4    ,			do_center_crop=_A    ,			do_normalize=_A    ,			do_resize=_A    ,			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      SCREAMING_SNAKE_CASE__ (      self				:      Dict       ):
        lowerCAmelCase_   :				Dict								= self.dummy_prior
        lowerCAmelCase_   :				List[str]								= self.dummy_image_encoder
        lowerCAmelCase_   :				Any								= self.dummy_text_encoder
        lowerCAmelCase_   :				Union[str, Any]								= self.dummy_tokenizer
        lowerCAmelCase_   :				Optional[int]								= self.dummy_image_processor

        lowerCAmelCase_   :				Any								= UnCLIPScheduler(
            variance_type='fixed_small_log'    ,			prediction_type='sample'    ,			num_train_timesteps=1_0_0_0    ,			clip_sample=_A    ,			clip_sample_range=10.0    ,			)

        lowerCAmelCase_   :				str								= {
            "prior": prior,
            "image_encoder": image_encoder,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "scheduler": scheduler,
            "image_processor": image_processor,
        }

        return components



      def      SCREAMING_SNAKE_CASE__ (      self				:      Tuple    ,			SCREAMING_SNAKE_CASE_				:      int    ,			SCREAMING_SNAKE_CASE_				:      Dict=0       ):






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



      def      SCREAMING_SNAKE_CASE__ (      self				:      Optional[int]       ):
        lowerCAmelCase_   :				Dict								= "cpu"

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

        lowerCAmelCase_   :				Union[str, Any]								= self.pipeline_class(**_A       )
        lowerCAmelCase_   :				List[str]								= pipe.to(_A       )

        pipe.set_progress_bar_config(disable=_A       )

        lowerCAmelCase_   :				List[str]								= pipe(**self.get_dummy_inputs(_A       )       )
        lowerCAmelCase_   :				int								= output.image_embeds

        lowerCAmelCase_   :				Any								= pipe(
            **self.get_dummy_inputs(_A       )    ,			return_dict=_A    ,			)[0]

        lowerCAmelCase_   :				Any								= image[0, -1_0:]
        lowerCAmelCase_   :				List[Any]								= image_from_tuple[0, -1_0:]

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

        lowerCAmelCase_   :				Optional[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      SCREAMING_SNAKE_CASE__ (      self				:      Any       ):
        lowerCAmelCase_   :				Optional[Any]								= torch_device == "cpu"
        lowerCAmelCase_   :				str								= True
        lowerCAmelCase_   :				List[str]								= False

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





      @skip_mps
      def      SCREAMING_SNAKE_CASE__ (      self				:      str       ):
        lowerCAmelCase_   :				List[str]								= torch_device == "cpu"
        lowerCAmelCase_   :				Dict								= False

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






from __future__ import annotations

from math import pi, sqrt




def       _snake_case	(   lowerCAmelCase							:   float   , lowerCAmelCase							:   float	):
		"""simple docstring"""







		if inductance <= 0:
				raise ValueError("Inductance cannot be 0 or negative"	)

		elif capacitance <= 0:
				raise ValueError("Capacitance cannot be 0 or negative"	)

		else:
				return (
				    "Resonant frequency",
				    float(1 / (2 * pi * (sqrt(inductance * capacitance	)))	),
				)


if __name__ == "__main__":
		import doctest

		doctest.testmod()
