






"""simple docstring"""







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  lowerCamelCase__ :






				def __init__(			self     ,A     ,A=13     ,A=30     ,A=2     ,A=3     ,A=True     ,A=True     ,A=32     ,A=2     ,A=4     ,A=37     ,A="gelu"     ,A=0.1     ,A=0.1     ,A=10     ,A=0.02     ,A=3     ,A=None     ,A=2     ,):
										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
										UpperCAmelCase          =	encoder_stride

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






				def     _UpperCamelCase							(			self ):
										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     _UpperCamelCase							(			self ):
										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     _UpperCamelCase							(			self     ,A     ,A     ,A ):
										UpperCAmelCase          =	TFDeiTModel(config=__lowerCAmelCase )
										UpperCAmelCase          =	model(__lowerCAmelCase )
										self.parent.assertEqual(result.last_hidden_state.shape     ,(self.batch_size, self.seq_length, self.hidden_size) )






				def     _UpperCamelCase							(			self     ,A     ,A     ,A ):
										UpperCAmelCase          =	TFDeiTForMaskedImageModeling(config=__lowerCAmelCase )
										UpperCAmelCase          =	model(__lowerCAmelCase )
										self.parent.assertEqual(
										    result.reconstruction.shape     ,(self.batch_size, self.num_channels, self.image_size, self.image_size) )

										# test greyscale images
										UpperCAmelCase          =	1
										UpperCAmelCase          =	TFDeiTForMaskedImageModeling(__lowerCAmelCase )

										UpperCAmelCase          =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
										UpperCAmelCase          =	model(__lowerCAmelCase )
										self.parent.assertEqual(result.reconstruction.shape     ,(self.batch_size, 1, self.image_size, self.image_size) )






				def     _UpperCamelCase							(			self     ,A     ,A     ,A ):
										UpperCAmelCase          =	self.type_sequence_label_size
										UpperCAmelCase          =	TFDeiTForImageClassification(__lowerCAmelCase )
										UpperCAmelCase          =	model(__lowerCAmelCase     ,labels=__lowerCAmelCase )
										self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size) )

										# test greyscale images
										UpperCAmelCase          =	1
										UpperCAmelCase          =	TFDeiTForImageClassification(__lowerCAmelCase )

										UpperCAmelCase          =	floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
										UpperCAmelCase          =	model(__lowerCAmelCase     ,labels=__lowerCAmelCase )
										self.parent.assertEqual(result.logits.shape     ,(self.batch_size, self.type_sequence_label_size) )






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







@require_tf
class  lowerCamelCase__ (	lowerCAmelCase_   ,					lowerCAmelCase_   ,					unittest.TestCase			):
				SCREAMING_SNAKE_CASE		=      (
				    (
				        TFDeiTModel,
				        TFDeiTForImageClassification,
				        TFDeiTForImageClassificationWithTeacher,
				        TFDeiTForMaskedImageModeling,
				    )
				    if is_tf_available()
				    else ()
				)
				SCREAMING_SNAKE_CASE		=      (
				    {
				        'feature-extraction': TFDeiTModel,
				        'image-classification': (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
				    }
				    if is_tf_available()
				    else {}
				)

				SCREAMING_SNAKE_CASE		=      False
				SCREAMING_SNAKE_CASE		=      False
				SCREAMING_SNAKE_CASE		=      False
				SCREAMING_SNAKE_CASE		=      False






				def     _UpperCamelCase							(			self ):
										UpperCAmelCase          =	TFDeiTModelTester(self )
										UpperCAmelCase          =	ConfigTester(self     ,config_class=__lowerCAmelCase     ,has_text_modality=__lowerCAmelCase     ,hidden_size=37 )






				def     _UpperCamelCase							(			self ):
										self.config_tester.run_common_tests()






				@unittest.skip(reason="""DeiT does not use inputs_embeds""" )
				def     _UpperCamelCase							(			self ):
										pass






				def     _UpperCamelCase							(			self ):
										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.Dense ) )






				def     _UpperCamelCase							(			self ):
										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     _UpperCamelCase							(			self ):
										UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_model(*__lowerCAmelCase )






				def     _UpperCamelCase							(			self ):
										UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCAmelCase )






				def     _UpperCamelCase							(			self ):
										UpperCAmelCase          =	self.model_tester.prepare_config_and_inputs()
										self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase )






				def     _UpperCamelCase							(			self     ,A     ,A     ,A=False ):
										UpperCAmelCase          =	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     _UpperCamelCase							(			self ):
										for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																UpperCAmelCase          =	TFDeiTModel.from_pretrained(__lowerCAmelCase )
																self.assertIsNotNone(__lowerCAmelCase )







def _a			(		):







						"""simple docstring"""






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







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






				@cached_property
				def     _UpperCamelCase							(			self ):
										return (
										    DeiTImageProcessor.from_pretrained("""facebook/deit-base-distilled-patch16-224""" )
										    if is_vision_available()
										    else None
										)






				@slow
				def     _UpperCamelCase							(			self ):
										UpperCAmelCase          =	TFDeiTForImageClassificationWithTeacher.from_pretrained("""facebook/deit-base-distilled-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, 1_000) )
										self.assertEqual(outputs.logits.shape     ,__lowerCAmelCase )

										UpperCAmelCase          =	tf.constant([-1.0266, 0.1912, -1.2861] )

										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 _a			(		_snake_case							):







      """simple docstring"""






      UpperCAmelCase          =	[]

      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(_snake_case				,	_snake_case							):
                  inputs.append(create_inputs(_snake_case							)							)
            else:
                  raise ValueError(F'''Invalid type requested: {input_type}'''							)

      return inputs

def _a			(		_snake_case							):







      """simple docstring"""






      UpperCAmelCase          =	[]

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

      return output_types







@is_tool_test
class  lowerCamelCase__ :






    def     _UpperCamelCase							(			self ):
          self.assertTrue(hasattr(self.tool     ,"""inputs""" ) )
          self.assertTrue(hasattr(self.tool     ,"""outputs""" ) )

          UpperCAmelCase          =	self.tool.inputs
          for _input in inputs:
                if isinstance(_input     ,A ):
                      for __input in _input:
                            self.assertTrue(__input in authorized_types )
                else:
                      self.assertTrue(_input in authorized_types )

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






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	create_inputs(self.tool.inputs )
          UpperCAmelCase          =	self.tool(*A )

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

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






    def     _UpperCamelCase							(			self ):
          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     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	create_inputs(self.tool.inputs )
          UpperCAmelCase          =	self.tool(*A )

          if not isinstance(A     ,A ):
                UpperCAmelCase          =	[outputs]

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

          for output, output_type in zip(A     ,self.tool.outputs ):
                UpperCAmelCase          =	AGENT_TYPE_MAPPING[output_type]
                self.assertTrue(isinstance(A     ,A ) )






    def     _UpperCamelCase							(			self ):
          UpperCAmelCase          =	create_inputs(self.tool.inputs )

          UpperCAmelCase          =	[]

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

          if not isinstance(A     ,A ):
                UpperCAmelCase          =	[outputs]

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



