



from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
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 (
       TFDeiTForImageClassification,
       TFDeiTForImageClassificationWithTeacher,
       TFDeiTForMaskedImageModeling,
       TFDeiTModel,
   )
   from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
   from PIL import Image

   from transformers import DeiTImageProcessor
class 					a	:



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[str]     			=parent
     SCREAMING_SNAKE_CASE_: int     			=batch_size
     SCREAMING_SNAKE_CASE_: Optional[int]     			=image_size
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=patch_size
     SCREAMING_SNAKE_CASE_: Optional[int]     			=num_channels
     SCREAMING_SNAKE_CASE_: Dict     			=is_training
     SCREAMING_SNAKE_CASE_: List[Any]     			=use_labels
     SCREAMING_SNAKE_CASE_: List[Any]     			=hidden_size
     SCREAMING_SNAKE_CASE_: Optional[int]     			=num_hidden_layers
     SCREAMING_SNAKE_CASE_: int     			=num_attention_heads
     SCREAMING_SNAKE_CASE_: Tuple     			=intermediate_size
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=hidden_act
     SCREAMING_SNAKE_CASE_: Any     			=hidden_dropout_prob
     SCREAMING_SNAKE_CASE_: Dict     			=attention_probs_dropout_prob
     SCREAMING_SNAKE_CASE_: Tuple     			=type_sequence_label_size
     SCREAMING_SNAKE_CASE_: Dict     			=initializer_range
     SCREAMING_SNAKE_CASE_: Optional[int]     			=scope
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=encoder_stride

     # in DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
     SCREAMING_SNAKE_CASE_: Tuple     			=(image_size // patch_size) ** 2
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=num_patches + 2



  def 	lowerCamelCase__       (						self :					Tuple		)     ->					List[str]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

     SCREAMING_SNAKE_CASE_: List[Any]     			=self.get_config()

     return config, pixel_values, labels



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


     '''simple docstring'''




     return DeiTConfig(
         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       ,		encoder_stride=self.encoder_stride       ,		)



  def 	lowerCamelCase__       (						self :					Union[str, Any]       ,		lowerCAmelCase :					int       ,		lowerCAmelCase :					Any       ,		lowerCAmelCase :					Any		)     ->					Dict:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=TFDeiTModel(config=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=model(lowerCAmelCase		)
     self.parent.assertEqual(result.last_hidden_state.shape       ,		(self.batch_size, self.seq_length, self.hidden_size)		)



  def 	lowerCamelCase__       (						self :					int       ,		lowerCAmelCase :					Optional[Any]       ,		lowerCAmelCase :					Optional[int]       ,		lowerCAmelCase :					Tuple		)     ->					Optional[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[Any]     			=TFDeiTForMaskedImageModeling(config=lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: str     			=model(lowerCAmelCase		)
     self.parent.assertEqual(
         result.reconstruction.shape       ,		(self.batch_size, self.num_channels, self.image_size, self.image_size)		)

     # test greyscale images
     SCREAMING_SNAKE_CASE_: str     			=1
     SCREAMING_SNAKE_CASE_: str     			=TFDeiTForMaskedImageModeling(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: List[str]     			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
     SCREAMING_SNAKE_CASE_: Any     			=model(lowerCAmelCase		)
     self.parent.assertEqual(result.reconstruction.shape       ,		(self.batch_size, 1, self.image_size, self.image_size)		)



  def 	lowerCamelCase__       (						self :					Any       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					str		)     ->					int:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[int]     			=self.type_sequence_label_size
     SCREAMING_SNAKE_CASE_: Dict     			=TFDeiTForImageClassification(lowerCAmelCase		)
     SCREAMING_SNAKE_CASE_: Tuple     			=model(lowerCAmelCase       ,		labels=lowerCAmelCase		)
     self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size)		)

     # test greyscale images
     SCREAMING_SNAKE_CASE_: List[str]     			=1
     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=TFDeiTForImageClassification(lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
     SCREAMING_SNAKE_CASE_: List[Any]     			=model(lowerCAmelCase       ,		labels=lowerCAmelCase		)
     self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size)		)





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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=self.prepare_config_and_inputs()
     SCREAMING_SNAKE_CASE_: Any     			=config_and_inputs
     SCREAMING_SNAKE_CASE_: Dict     			={'pixel_values': pixel_values}
     return config, inputs_dict







@require_tf
class 					a	(  __A	,      __A	,      unittest.TestCase       ):
  UpperCamelCase	:				Dict     						=					(
      (
          TFDeiTModel,
          TFDeiTForImageClassification,
          TFDeiTForImageClassificationWithTeacher,
          TFDeiTForMaskedImageModeling,
      )
      if is_tf_available()
      else ()
  )
  UpperCamelCase	:				Dict     						=					(
      {
          'feature-extraction': TFDeiTModel,
          'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
      }
      if is_tf_available()
      else {}
  )

  UpperCamelCase	:				Union[str, Any]     						=					False
  UpperCamelCase	:				List[str]     						=					False
  UpperCamelCase	:				int     						=					False
  UpperCamelCase	:				Tuple     						=					False



  def 	lowerCamelCase__       (						self :					Dict		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=TFDeiTModelTester(self		)
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=ConfigTester(self       ,		config_class=lowerCAmelCase       ,		has_text_modality=lowerCAmelCase       ,		hidden_size=37		)



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


     '''simple docstring'''




     self.config_tester.run_common_tests()



  @unittest.skip(reason="""DeiT does not use inputs_embeds"""		)
  def 	lowerCamelCase__       (						self :					Union[str, Any]		)     ->					Any:


     '''simple docstring'''




     pass



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: str     			=self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        SCREAMING_SNAKE_CASE_: Union[str, Any]     			=model_class(lowerCAmelCase		)
        self.assertIsInstance(model.get_input_embeddings()       ,		(tf.keras.layers.Layer)		)
        SCREAMING_SNAKE_CASE_: str     			=model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(lowerCAmelCase       ,		tf.keras.layers.Dense		)		)



  def 	lowerCamelCase__       (						self :					Any		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Any     			=self.model_tester.prepare_config_and_inputs_for_common()

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

        SCREAMING_SNAKE_CASE_: List[Any]     			=['pixel_values']
        self.assertListEqual(arg_names[:1]       ,		lowerCAmelCase		)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: int     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase		)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Optional[int]     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase		)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Any     			=self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase		)



  def 	lowerCamelCase__       (						self :					Optional[int]       ,		lowerCAmelCase :					List[Any]       ,		lowerCAmelCase :					Union[str, Any]       ,		lowerCAmelCase :					Dict=False		)     ->					Any:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: List[str]     			=super()._prepare_for_class(lowerCAmelCase       ,		lowerCAmelCase       ,		return_labels=lowerCAmelCase		)

     if return_labels:
        if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call		).parameters:
           del inputs_dict["labels"]

     return inputs_dict





  @slow
  def 	lowerCamelCase__       (						self :					List[str]		)     ->					Tuple:


     '''simple docstring'''




     for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        SCREAMING_SNAKE_CASE_: Optional[int]     			=TFDeiTModel.from_pretrained(lowerCAmelCase		)
        self.assertIsNotNone(lowerCAmelCase		)







def      __magic_name__				(							):
   SCREAMING_SNAKE_CASE_: Any     			=Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
   return image
@require_tf
@require_vision
class 					a	(  unittest.TestCase       ):



  @cached_property
  def 	lowerCamelCase__       (						self :					Any		)     ->					Dict:


     '''simple docstring'''




     return (
         DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224"""		)
         if is_vision_available()
         else None
     )





  @slow
  def 	lowerCamelCase__       (						self :					List[str]		)     ->					int:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-patch16-224"""		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=self.default_image_processor
     SCREAMING_SNAKE_CASE_: List[Any]     			=prepare_img()
     SCREAMING_SNAKE_CASE_: Any     			=image_processor(images=lowerCAmelCase       ,		return_tensors="""tf"""		)

     # forward pass
     SCREAMING_SNAKE_CASE_: Optional[Any]     			=model(**lowerCAmelCase		)

     # verify the logits
     SCREAMING_SNAKE_CASE_: str     			=tf.TensorShape((1, 1000)		)
     self.assertEqual(outputs.logits.shape       ,		lowerCAmelCase		)

     SCREAMING_SNAKE_CASE_: Tuple     			=tf.constant([-1.0_2_6_6, 0.1_9_1_2, -1.2_8_6_1]		)

     self.assertTrue(np.allclose(outputs.logits[0, :3]       ,		lowerCAmelCase       ,		atol=1E-4		)		)








"""simple docstring"""
from pathlib import Path
from typing import List

from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image


_UpperCAmelCase     =			["""text""", """image""", """audio"""]





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: str     			=[]

   for input_type in input_types:
      if input_type == "text":
         inputs.append("""Text input""" )
      elif input_type == "image":
         inputs.append(
             Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO""" ) ) / """000000039769.png""" ).resize((512, 512) ) )
      elif input_type == "audio":
         inputs.append(torch.ones(3000 ) )
      elif isinstance(lowercase							,			lowercase ):
         inputs.append(create_inputs(lowercase ) )
      else:
         raise ValueError(f'''Invalid type requested: {input_type}''' )

   return inputs





def      __magic_name__				(							lowercase ):
   SCREAMING_SNAKE_CASE_: int     			=[]

   for output in outputs:
      if isinstance(lowercase							,			(str, AgentText) ):
         output_types.append("""text""" )
      elif isinstance(lowercase							,			(Image.Image, AgentImage) ):
         output_types.append("""image""" )
      elif isinstance(lowercase							,			(torch.Tensor, AgentAudio) ):
         output_types.append("""audio""" )
      else:
         raise ValueError(f'''Invalid output: {output}''' )

   return output_types
@is_tool_test
class 					a	:



  def 	lowerCamelCase__       (						self :					Tuple		)     ->					List[Any]:


     '''simple docstring'''




     self.assertTrue(hasattr(self.tool       ,		"""inputs"""		)		)
     self.assertTrue(hasattr(self.tool       ,		"""outputs"""		)		)

     SCREAMING_SNAKE_CASE_: Optional[int]     			=self.tool.inputs
     for _input in inputs:
        if isinstance(_input       ,		lowerCAmelCase		):
           for __input in _input:
              self.assertTrue(__input in authorized_types		)
        else:
           self.assertTrue(_input in authorized_types		)

     SCREAMING_SNAKE_CASE_: Any     			=self.tool.outputs
     for _output in outputs:
        self.assertTrue(_output in authorized_types		)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Dict     			=create_inputs(self.tool.inputs		)
     SCREAMING_SNAKE_CASE_: List[Any]     			=self.tool(*lowerCAmelCase		)

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

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



  def 	lowerCamelCase__       (						self :					str		)     ->					Optional[Any]:


     '''simple docstring'''




     self.assertTrue(hasattr(self.tool       ,		"""description"""		)		)
     self.assertTrue(hasattr(self.tool       ,		"""default_checkpoint"""		)		)
     self.assertTrue(self.tool.description.startswith("""This is a tool that"""		)		)



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


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: str     			=create_inputs(self.tool.inputs		)
     SCREAMING_SNAKE_CASE_: Tuple     			=self.tool(*lowerCAmelCase		)

     if not isinstance(lowerCAmelCase       ,		lowerCAmelCase		):
        SCREAMING_SNAKE_CASE_: int     			=[outputs]

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

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





  def 	lowerCamelCase__       (						self :					List[Any]		)     ->					List[Any]:


     '''simple docstring'''




     SCREAMING_SNAKE_CASE_: Tuple     			=create_inputs(self.tool.inputs		)

     SCREAMING_SNAKE_CASE_: Union[str, Any]     			=[]

     for _input, input_type in zip(lowerCAmelCase       ,		self.tool.inputs		):
        if isinstance(lowerCAmelCase       ,		lowerCAmelCase		):
           _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
     SCREAMING_SNAKE_CASE_: Dict     			=self.tool(*lowerCAmelCase		)

     if not isinstance(lowerCAmelCase       ,		lowerCAmelCase		):
        SCREAMING_SNAKE_CASE_: List[str]     			=[outputs]

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



