





from __future__ import annotations

import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
     import tensorflow as tf

     from transformers import TFViTForImageClassification, TFViTModel


if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor

class   A							:



      def __init__(						self:    Any		,	_lowerCAmelCase:    str		,	_lowerCAmelCase:    Optional[Any]=13		,	_lowerCAmelCase:    List[str]=30		,	_lowerCAmelCase:    List[Any]=2		,	_lowerCAmelCase:    List[str]=3		,	_lowerCAmelCase:    Dict=True		,	_lowerCAmelCase:    int=True		,	_lowerCAmelCase:    Tuple=32		,	_lowerCAmelCase:    str=2		,	_lowerCAmelCase:    Dict=4		,	_lowerCAmelCase:    Dict=37		,	_lowerCAmelCase:    Optional[Any]="gelu"		,	_lowerCAmelCase:    List[Any]=0.1		,	_lowerCAmelCase:    List[Any]=0.1		,	_lowerCAmelCase:    Union[str, Any]=10		,	_lowerCAmelCase:    str=0.02		,	_lowerCAmelCase:    Optional[Any]=3		,	_lowerCAmelCase:    Optional[int]=None		,	)    ->     Any:
         '''simple docstring'''

         UpperCAmelCase_           =parent
         UpperCAmelCase_           =batch_size
         UpperCAmelCase_           =image_size
         UpperCAmelCase_           =patch_size
         UpperCAmelCase_           =num_channels
         UpperCAmelCase_           =is_training
         UpperCAmelCase_           =use_labels
         UpperCAmelCase_           =hidden_size
         UpperCAmelCase_           =num_hidden_layers
         UpperCAmelCase_           =num_attention_heads
         UpperCAmelCase_           =intermediate_size
         UpperCAmelCase_           =hidden_act
         UpperCAmelCase_           =hidden_dropout_prob
         UpperCAmelCase_           =attention_probs_dropout_prob
         UpperCAmelCase_           =type_sequence_label_size
         UpperCAmelCase_           =initializer_range
         UpperCAmelCase_           =scope

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         UpperCAmelCase_           =(image_size // patch_size) ** 2
         UpperCAmelCase_           =num_patches + 1



      def 						lowerCAmelCase__     (						self:    Any							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_           =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

         UpperCAmelCase_           =None
         if self.use_labels:
            UpperCAmelCase_           =ids_tensor([self.batch_size]		,	self.type_sequence_label_size							)

         UpperCAmelCase_           =self.get_config()

         return config, pixel_values, labels



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Dict:
         '''simple docstring'''

         return ViTConfig(
             image_size=self.image_size		,	patch_size=self.patch_size		,	num_channels=self.num_channels		,	hidden_size=self.hidden_size		,	num_hidden_layers=self.num_hidden_layers		,	num_attention_heads=self.num_attention_heads		,	intermediate_size=self.intermediate_size		,	hidden_act=self.hidden_act		,	hidden_dropout_prob=self.hidden_dropout_prob		,	attention_probs_dropout_prob=self.attention_probs_dropout_prob		,	is_decoder=_lowerCAmelCase		,	initializer_range=self.initializer_range		,	)



      def 						lowerCAmelCase__     (						self:    List[Any]		,	_lowerCAmelCase:    int		,	_lowerCAmelCase:    Any		,	_lowerCAmelCase:    List[str]							)    ->     Dict:
         '''simple docstring'''

         UpperCAmelCase_           =TFViTModel(config=_lowerCAmelCase							)
         UpperCAmelCase_           =model(_lowerCAmelCase		,	training=_lowerCAmelCase							)
         self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, self.seq_length, self.hidden_size)							)

         # Test with an image with different size than the one specified in config.
         UpperCAmelCase_           =self.image_size // 2
         UpperCAmelCase_           =pixel_values[:, :, :image_size, :image_size]
         UpperCAmelCase_           =model(_lowerCAmelCase		,	interpolate_pos_encoding=_lowerCAmelCase		,	training=_lowerCAmelCase							)
         UpperCAmelCase_           =(image_size // self.patch_size) ** 2 + 1
         self.parent.assertEqual(result.last_hidden_state.shape		,	(self.batch_size, seq_length, self.hidden_size)							)



      def 						lowerCAmelCase__     (						self:    Optional[int]		,	_lowerCAmelCase:    Optional[Any]		,	_lowerCAmelCase:    List[Any]		,	_lowerCAmelCase:    List[Any]							)    ->     Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_           =self.type_sequence_label_size
         UpperCAmelCase_           =TFViTForImageClassification(_lowerCAmelCase							)
         UpperCAmelCase_           =model(_lowerCAmelCase		,	labels=_lowerCAmelCase		,	training=_lowerCAmelCase							)
         self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)							)

         # Test with an image with different size than the one specified in config.
         UpperCAmelCase_           =self.image_size // 2
         UpperCAmelCase_           =pixel_values[:, :, :image_size, :image_size]
         UpperCAmelCase_           =model(_lowerCAmelCase		,	interpolate_pos_encoding=_lowerCAmelCase		,	training=_lowerCAmelCase							)
         self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)							)

         # test greyscale images
         UpperCAmelCase_           =1
         UpperCAmelCase_           =TFViTForImageClassification(_lowerCAmelCase							)
         UpperCAmelCase_           =floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
         UpperCAmelCase_           =model(_lowerCAmelCase							)
         self.parent.assertEqual(result.logits.shape		,	(self.batch_size, self.type_sequence_label_size)							)






      def 						lowerCAmelCase__     (						self:    Any							)    ->     Optional[int]:
         '''simple docstring'''

         UpperCAmelCase_           =self.prepare_config_and_inputs()
         UpperCAmelCase_    ,							UpperCAmelCase_    ,							UpperCAmelCase_           =config_and_inputs
         UpperCAmelCase_           ={"pixel_values": pixel_values}
         return config, inputs_dict

@require_tf
class   A							(						__lowercase		,   __lowercase		,   unittest.TestCase    ):
      _snake_case				  =(TFViTModel, TFViTForImageClassification) if is_tf_available() else ()
      _snake_case				  =(
          {'''feature-extraction''': TFViTModel, '''image-classification''': TFViTForImageClassification}
          if is_tf_available()
          else {}
      )

      _snake_case				  =False
      _snake_case				  =False
      _snake_case				  =False



      def 						lowerCAmelCase__     (						self:    int							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_           =TFViTModelTester(self							)
         UpperCAmelCase_           =ConfigTester(self		,	config_class=_lowerCAmelCase		,	has_text_modality=_lowerCAmelCase		,	hidden_size=37							)



      def 						lowerCAmelCase__     (						self:    Optional[Any]							)    ->     str:
         '''simple docstring'''

         self.config_tester.run_common_tests()



      @unittest.skip(reason="ViT does not use inputs_embeds"							)
      def 						lowerCAmelCase__     (						self:    Dict							)    ->     Tuple:
         '''simple docstring'''

         pass



      @unittest.skip(reason="ViT does not use inputs_embeds"							)
      def 						lowerCAmelCase__     (						self:    int							)    ->     Optional[Any]:
         '''simple docstring'''

         pass



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Tuple:
         '''simple docstring'''

         UpperCAmelCase_    ,							UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase_           =model_class(_lowerCAmelCase							)
            self.assertIsInstance(model.get_input_embeddings()		,	(tf.keras.layers.Layer)							)
            UpperCAmelCase_           =model.get_output_embeddings()
            self.assertTrue(x is None or isinstance(_lowerCAmelCase		,	tf.keras.layers.Layer							)							)



      def 						lowerCAmelCase__     (						self:    List[str]							)    ->     int:
         '''simple docstring'''

         UpperCAmelCase_    ,							UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
            UpperCAmelCase_           =model_class(_lowerCAmelCase							)
            UpperCAmelCase_           =inspect.signature(model.call							)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCAmelCase_           =[*signature.parameters.keys()]

            UpperCAmelCase_           =["pixel_values"]
            self.assertListEqual(arg_names[:1]		,	_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    int							)    ->     Optional[int]:
         '''simple docstring'''

         UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_lowerCAmelCase							)



      def 						lowerCAmelCase__     (						self:    List[Any]							)    ->     Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_           =self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_lowerCAmelCase							)






      @slow
      def 						lowerCAmelCase__     (						self:    Optional[Any]							)    ->     Tuple:
         '''simple docstring'''

         UpperCAmelCase_           =TFViTModel.from_pretrained("google/vit-base-patch16-224"							)
         self.assertIsNotNone(_lowerCAmelCase							)




def      a__			(       ):






   '''simple docstring'''






   UpperCAmelCase_           =Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"	)
   return image





@require_tf
@require_vision
class   A							(						unittest.TestCase    ):



      @cached_property
      def 						lowerCAmelCase__     (						self:    Union[str, Any]							)    ->     Union[str, Any]:
         '''simple docstring'''

         return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"							) if is_vision_available() else None






      @slow
      def 						lowerCAmelCase__     (						self:    Dict							)    ->     Optional[Any]:
         '''simple docstring'''

         UpperCAmelCase_           =TFViTForImageClassification.from_pretrained("google/vit-base-patch16-224"							)

         UpperCAmelCase_           =self.default_image_processor
         UpperCAmelCase_           =prepare_img()
         UpperCAmelCase_           =image_processor(images=_lowerCAmelCase		,	return_tensors="tf"							)

         # forward pass
         UpperCAmelCase_           =model(**_lowerCAmelCase							)

         # verify the logits
         UpperCAmelCase_           =tf.TensorShape((1, 1000)							)
         self.assertEqual(outputs.logits.shape		,	_lowerCAmelCase							)

         UpperCAmelCase_           =tf.constant([-0.27_44, 0.82_15, -0.08_36]							)

         tf.debugging.assert_near(outputs.logits[0, :3]		,	_lowerCAmelCase		,	atol=1e-4							)









'''simple docstring'''





import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()



class  snake_case__						(    SCREAMING_SNAKE_CASE_  ,     unittest.TestCase				):
 A__				= KandinskyInpaintPipeline
 A__				= ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
 A__				= [
     '''prompt''',
     '''negative_prompt''',
     '''image_embeds''',
     '''negative_image_embeds''',
     '''image''',
     '''mask_image''',
 ]
 A__				= [
     '''generator''',
     '''height''',
     '''width''',
     '''latents''',
     '''guidance_scale''',
     '''negative_prompt''',
     '''num_inference_steps''',
     '''return_dict''',
     '''guidance_scale''',
     '''num_images_per_prompt''',
     '''output_type''',
     '''return_dict''',
 ]
 A__				= False
 @property
 def A_   (   self						:							Dict  )      ->   Union[str, Any]:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Optional[int]  )      ->   Tuple:







       '''simple docstring'''
       return 32
 @property
 def A_   (   self						:							Dict  )      ->   str:







       '''simple docstring'''
       return self.time_input_dim
 @property
 def A_   (   self						:							Dict  )      ->   Any:







       '''simple docstring'''
       return self.time_input_dim * 4
 @property
 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       return 100
 @property
 def A_   (   self						:							int  )      ->   Union[str, Any]:







       '''simple docstring'''
       __snake_case :   List[str]													=    XLMRobertaTokenizerFast.from_pretrained('YiYiXu/tiny-random-mclip-base'  )
       return tokenizer
 @property
 def A_   (   self						:							Tuple  )      ->   str:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   str													=    MCLIPConfig(
           numDims=self.cross_attention_dim      ,     transformerDimensions=self.text_embedder_hidden_size      ,     hidden_size=self.text_embedder_hidden_size      ,     intermediate_size=37      ,     num_attention_heads=4      ,     num_hidden_layers=5      ,     vocab_size=1005      ,     )

       __snake_case :   List[Any]													=    MultilingualCLIP(__a  )
       __snake_case :   List[str]													=    text_encoder.eval()

       return text_encoder
 @property
 def A_   (   self						:							Dict  )      ->   List[str]:







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

       __snake_case :   Tuple													=    {
           'in_channels': 9,
           # Out channels is double in channels because predicts mean and variance
           'out_channels': 8,
           'addition_embed_type': 'text_image',
           'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
           'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
           'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
           'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
           'layers_per_block': 1,
           'encoder_hid_dim': self.text_embedder_hidden_size,
           'encoder_hid_dim_type': 'text_image_proj',
           'cross_attention_dim': self.cross_attention_dim,
           'attention_head_dim': 4,
           'resnet_time_scale_shift': 'scale_shift',
           'class_embed_type': None,
       }

       __snake_case :   Any													=    UNetaDConditionModel(**__a  )
       return model
 @property
 def A_   (   self						:							List[str]  )      ->   List[Any]:







       '''simple docstring'''
       return {
           "block_out_channels": [32, 64],
           "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
           "in_channels": 3,
           "latent_channels": 4,
           "layers_per_block": 1,
           "norm_num_groups": 8,
           "norm_type": "spatial",
           "num_vq_embeddings": 12,
           "out_channels": 3,
           "up_block_types": [
               "AttnUpDecoderBlock2D",
               "UpDecoderBlock2D",
           ],
           "vq_embed_dim": 4,
       }
 @property
 def A_   (   self						:							int  )      ->   List[str]:







       '''simple docstring'''
       torch.manual_seed(0  )
       __snake_case :   Optional[int]													=    VQModel(**self.dummy_movq_kwargs  )
       return model
 def A_   (   self						:							Dict  )      ->   Tuple:







       '''simple docstring'''
       __snake_case :   Tuple													=    self.dummy_text_encoder
       __snake_case :   str													=    self.dummy_tokenizer
       __snake_case :   Any													=    self.dummy_unet
       __snake_case :   Optional[Any]													=    self.dummy_movq

       __snake_case :   Optional[Any]													=    DDIMScheduler(
           num_train_timesteps=1000      ,     beta_schedule='linear'      ,     beta_start=0.0_0_0_8_5      ,     beta_end=0.0_1_2      ,     clip_sample=__a      ,     set_alpha_to_one=__a      ,     steps_offset=1      ,     prediction_type='epsilon'      ,     thresholding=__a      ,     )

       __snake_case :   List[str]													=    {
           'text_encoder': text_encoder,
           'tokenizer': tokenizer,
           'unet': unet,
           'scheduler': scheduler,
           'movq': movq,
       }

       return components
 def A_   (   self						:							List[str]      ,     __a						:							Dict      ,     __a						:							int=0  )      ->   Optional[Any]:







       '''simple docstring'''
       __snake_case :   int													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   str													=    floats_tensor((1, self.cross_attention_dim)      ,     rng=random.Random(seed + 1  )  ).to(__a  )
       # create init_image
       __snake_case :   Any													=    floats_tensor((1, 3, 64, 64)      ,     rng=random.Random(__a  )  ).to(__a  )
       __snake_case :   Optional[int]													=    image.cpu().permute(0      ,     2      ,     3      ,     1  )[0]
       __snake_case :   List[str]													=    Image.fromarray(np.uinta(__a  )  ).convert('RGB'  ).resize((256, 256)  )
       # create mask
       __snake_case :   Optional[int]													=    np.ones((64, 64)      ,     dtype=np.floataa  )
       __snake_case :   List[Any]													=    0

       if str(__a  ).startswith('mps'  ):
             __snake_case :   Any													=    torch.manual_seed(__a  )
       else:
             __snake_case :   Optional[int]													=    torch.Generator(device=__a  ).manual_seed(__a  )
       __snake_case :   int													=    {
           'prompt': 'horse',
           'image': init_image,
           'mask_image': mask,
           'image_embeds': image_embeds,
           'negative_image_embeds': negative_image_embeds,
           'generator': generator,
           'height': 64,
           'width': 64,
           'num_inference_steps': 2,
           'guidance_scale': 4.0,
           'output_type': 'np',
       }
       return inputs
 def A_   (   self						:							Any  )      ->   int:







       '''simple docstring'''
       __snake_case :   List[str]													=    'cpu'

       __snake_case :   Tuple													=    self.get_dummy_components()

       __snake_case :   Optional[int]													=    self.pipeline_class(**__a  )
       __snake_case :   Union[str, Any]													=    pipe.to(__a  )

       pipe.set_progress_bar_config(disable=__a  )

       __snake_case :   Optional[Any]													=    pipe(**self.get_dummy_inputs(__a  )  )
       __snake_case :   Dict													=    output.images

       __snake_case :   Union[str, Any]													=    pipe(
           **self.get_dummy_inputs(__a  )      ,     return_dict=__a      ,     )[0]

       __snake_case :   int													=    image[0, -3:, -3:, -1]
       __snake_case :   Optional[int]													=    image_from_tuple[0, -3:, -3:, -1]

       print(f'''image.shape {image.shape}'''  )

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

       __snake_case :   List[Any]													=    np.array(
           [0.8_3_2_6_9_1_9, 0.7_3_7_9_0_4_6_7, 0.2_0_9_1_8_5_8_1, 0.9_3_0_9_6_1_2, 0.5_5_1_1_7_9_1, 0.4_3_7_1_3_3_2_8, 0.5_5_1_3_3_2_1, 0.4_9_9_2_2_9_3_4, 0.5_9_4_9_7_7_8_6]  )

       assert (
           np.abs(image_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
       assert (
           np.abs(image_from_tuple_slice.flatten() - expected_slice  ).max() < 1e-2
       ), f''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''





 def A_   (   self						:							List[Any]  )      ->   List[str]:







       '''simple docstring'''
       super().test_inference_batch_single_identical(expected_max_diff=3e-3  )



@slow
@require_torch_gpu
class  snake_case__						(    unittest.TestCase				):
 def A_   (   self						:							Dict  )      ->   List[str]:







       '''simple docstring'''
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





 def A_   (   self						:							Optional[int]  )      ->   List[Any]:







       '''simple docstring'''
       __snake_case :   Union[str, Any]													=    load_numpy(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
           '/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy'  )

       __snake_case :   Tuple													=    load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinsky/cat.png'  )
       __snake_case :   Tuple													=    np.ones((768, 768)      ,     dtype=np.floataa  )
       __snake_case :   Tuple													=    0

       __snake_case :   Tuple													=    'a hat'

       __snake_case :   Optional[Any]													=    KandinskyPriorPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-prior'      ,     torch_dtype=torch.floataa  )
       pipe_prior.to(__a  )

       __snake_case :   int													=    KandinskyInpaintPipeline.from_pretrained(
           'kandinsky-community/kandinsky-2-1-inpaint'      ,     torch_dtype=torch.floataa  )
       __snake_case :   Optional[Any]													=    pipeline.to(__a  )
       pipeline.set_progress_bar_config(disable=__a  )

       __snake_case :   Any													=    torch.Generator(device='cpu'  ).manual_seed(0  )
       __snake_case							,     __snake_case :   Union[str, Any]													=    pipe_prior(
           __a      ,     generator=__a      ,     num_inference_steps=5      ,     negative_prompt=''      ,     ).to_tuple()

       __snake_case :   List[str]													=    pipeline(
           __a      ,     image=__a      ,     mask_image=__a      ,     image_embeds=__a      ,     negative_image_embeds=__a      ,     generator=__a      ,     num_inference_steps=100      ,     height=768      ,     width=768      ,     output_type='np'      ,     )

       __snake_case :   int													=    output.images[0]

       assert image.shape == (768, 768, 3)

       assert_mean_pixel_difference(__a      ,     __a  )



