






import unittest

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

from diffusers import KandinskyPriorPipeline, 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 ):
      lowerCamelCase_							:   Tuple											=	KandinskyPriorPipeline
      lowerCamelCase_							:   int											=	['prompt']
      lowerCamelCase_							:   str											=	['prompt', 'negative_prompt']
      lowerCamelCase_							:   Any											=	[
          'num_images_per_prompt',
          'generator',
          'num_inference_steps',
          'latents',
          'negative_prompt',
          'guidance_scale',
          'output_type',
          'return_dict',
      ]
      lowerCamelCase_							:   int											=	False






      @property
      def      UpperCAmelCase_     (self					:    Tuple		)       ->   str:


       """simple docstring"""






       return 32






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


       """simple docstring"""






       return 32






      @property
      def      UpperCAmelCase_     (self					:    Dict		)       ->   Dict:


       """simple docstring"""






       return self.time_input_dim






      @property
      def      UpperCAmelCase_     (self					:    List[str]		)       ->   Optional[int]:


       """simple docstring"""






       return self.time_input_dim * 4






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


       """simple docstring"""






       return 100






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


       """simple docstring"""






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






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


       """simple docstring"""






       torch.manual_seed(0		)
       lowerCamelCase_							:    Dict							=     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					:    List[Any]		)       ->   Dict:


       """simple docstring"""






       torch.manual_seed(0		)

       lowerCamelCase_							:    int							=     {
           'num_attention_heads': 2,
           'attention_head_dim': 12,
           'embedding_dim': self.text_embedder_hidden_size,
           'num_layers': 1,
       }

       lowerCamelCase_							:    Tuple							=     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
       lowerCamelCase_							:    Optional[Any]							=     nn.Parameter(torch.ones(model.clip_std.shape		)		)
       return model






      @property
      def      UpperCAmelCase_     (self					:    Dict		)       ->   int:


       """simple docstring"""






       torch.manual_seed(0		)
       lowerCamelCase_							:    Optional[int]							=     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		,		)

       lowerCamelCase_							:    Union[str, Any]							=     CLIPVisionModelWithProjection(_snake_case		)
       return model






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


       """simple docstring"""






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


       """simple docstring"""






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

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

       lowerCamelCase_							:    List[str]							=     {
           'prior': prior,
           'image_encoder': image_encoder,
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'scheduler': scheduler,
           'image_processor': image_processor,
       }

       return components






      def      UpperCAmelCase_     (self					:    Any		,		_snake_case					:    Tuple		,		_snake_case					:    Optional[Any]=0		)       ->   str:


       """simple docstring"""






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






      def      UpperCAmelCase_     (self					:    Dict		)       ->   Optional[int]:


       """simple docstring"""






       lowerCamelCase_							:    Dict							=     'cpu'

       lowerCamelCase_							:    Tuple							=     self.get_dummy_components()

       lowerCamelCase_							:    List[Any]							=     self.pipeline_class(**_snake_case		)
       lowerCamelCase_							:    Optional[Any]							=     pipe.to(_snake_case		)

       pipe.set_progress_bar_config(disable=_snake_case		)

       lowerCamelCase_							:    Optional[Any]							=     pipe(**self.get_dummy_inputs(_snake_case		)		)
       lowerCamelCase_							:    List[Any]							=     output.image_embeds

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

       lowerCamelCase_							:    List[str]							=     image[0, -10:]
       lowerCamelCase_							:    Union[str, Any]							=     image_from_tuple[0, -10:]

       assert image.shape == (1, 32)

       lowerCamelCase_							:    Dict							=     np.array(
           [-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156]		)

       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]		)       ->   Optional[int]:


       """simple docstring"""






       lowerCamelCase_							:    int							=     torch_device == 'cpu'
       lowerCamelCase_							:    Dict							=     True
       lowerCamelCase_							:    Tuple							=     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					:    str		)       ->   int:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     torch_device == 'cpu'
       lowerCamelCase_							:    Union[str, Any]							=     False

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








import unittest

from transformers import load_tool
from transformers.tools.agent_types import AGENT_TYPE_MAPPING

from .test_tools_common import ToolTesterMixin, output_types




class 	lowerCamelCase__				(							unittest.TestCase,   UpperCAmelCase ):






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


       """simple docstring"""






       lowerCamelCase_							:    str							=     load_tool('translation'		)
       self.tool.setup()
       lowerCamelCase_							:    Optional[int]							=     load_tool('translation'		,		remote=_snake_case		)






      def      UpperCAmelCase_     (self					:    Any		)       ->   Dict:


       """simple docstring"""






       lowerCamelCase_							:    Optional[Any]							=     self.tool('Hey, what\'s up?'		,		src_lang='English'		,		tgt_lang='French'		)
       self.assertEqual(_snake_case		,		'- Hé, comment ça va?'		)






      def      UpperCAmelCase_     (self					:    Optional[int]		)       ->   Dict:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     self.remote_tool('Hey, what\'s up?'		,		src_lang='English'		,		tgt_lang='French'		)
       self.assertEqual(_snake_case		,		'- Hé, comment ça va?'		)






      def      UpperCAmelCase_     (self					:    List[str]		)       ->   Optional[int]:


       """simple docstring"""






       lowerCamelCase_							:    Union[str, Any]							=     self.tool(text='Hey, what\'s up?'		,		src_lang='English'		,		tgt_lang='French'		)
       self.assertEqual(_snake_case		,		'- Hé, comment ça va?'		)






      def      UpperCAmelCase_     (self					:    Any		)       ->   Tuple:


       """simple docstring"""






       lowerCamelCase_							:    Optional[int]							=     self.remote_tool(text='Hey, what\'s up?'		,		src_lang='English'		,		tgt_lang='French'		)
       self.assertEqual(_snake_case		,		'- Hé, comment ça va?'		)






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


       """simple docstring"""






       lowerCamelCase_							:    str							=     ['Hey, what\'s up?', 'English', 'Spanish']
       lowerCamelCase_							:    Any							=     self.tool(*_snake_case		)

       # There is a single output
       if len(self.tool.outputs		) == 1:
        lowerCamelCase_							:    Any							=     [outputs]

       self.assertListEqual(output_types(_snake_case		)		,		self.tool.outputs		)






      def      UpperCAmelCase_     (self					:    Tuple		)       ->   Optional[Any]:


       """simple docstring"""






       lowerCamelCase_							:    List[str]							=     ['Hey, what\'s up?', 'English', 'Spanish']
       lowerCamelCase_							:    Optional[Any]							=     self.tool(*_snake_case		)

       if not isinstance(_snake_case		,		_snake_case		):
        lowerCamelCase_							:    List[str]							=     [outputs]

       self.assertEqual(len(_snake_case		)		,		len(self.tool.outputs		)		)

       for output, output_type in zip(_snake_case		,		self.tool.outputs		):
        lowerCamelCase_							:    Optional[int]							=     AGENT_TYPE_MAPPING[output_type]
        self.assertTrue(isinstance(_snake_case		,		_snake_case		)		)






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


       """simple docstring"""






       lowerCamelCase_							:    Dict							=     ['Hey, what\'s up?', 'English', 'Spanish']

       lowerCamelCase_							:    List[str]							=     []

       for _input, input_type in zip(_snake_case		,		self.tool.inputs		):
        if isinstance(_snake_case		,		_snake_case		):
         _inputs.append([AGENT_TYPE_MAPPING[_input_type](_input		) for _input_type in input_type]		)
        else:
         _inputs.append(AGENT_TYPE_MAPPING[input_type](_input		)		)

        # Should not raise an error
       lowerCamelCase_							:    Any							=     self.tool(*_snake_case		)

       if not isinstance(_snake_case		,		_snake_case		):
        lowerCamelCase_							:    Optional[Any]							=     [outputs]

       self.assertEqual(len(_snake_case		)		,		len(self.tool.outputs		)		)
