
"""simple docstring"""




import inspect
import unittest
from math import floor

from transformers import CvtConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import CvtForImageClassification, CvtModel
    from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor




class      __A(    __snake_case			):

  """simple docstring"""







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.config_class(**self.inputs_dict						)
       self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_	,      """embed_dim"""						)						)
       self.parent.assertTrue(hasattr(SCREAMING_SNAKE_CASE_	,      """num_heads"""						)						)






class      __A:

  """simple docstring"""







  def __init__(self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_=13	,      SCREAMING_SNAKE_CASE_=64	,      SCREAMING_SNAKE_CASE_=3	,      SCREAMING_SNAKE_CASE_=[16, 48, 96]	,      SCREAMING_SNAKE_CASE_=[1, 3, 6]	,      SCREAMING_SNAKE_CASE_=[1, 2, 10]	,      SCREAMING_SNAKE_CASE_=[7, 3, 3]	,      SCREAMING_SNAKE_CASE_=[4, 2, 2]	,      SCREAMING_SNAKE_CASE_=[2, 1, 1]	,      SCREAMING_SNAKE_CASE_=[2, 2, 2]	,      SCREAMING_SNAKE_CASE_=[False, False, True]	,      SCREAMING_SNAKE_CASE_=[0.0, 0.0, 0.0]	,      SCREAMING_SNAKE_CASE_=0.02	,      SCREAMING_SNAKE_CASE_=1E-12	,      SCREAMING_SNAKE_CASE_=True	,      SCREAMING_SNAKE_CASE_=True	,      SCREAMING_SNAKE_CASE_=2	,      ):
       UpperCamelCase__				=    parent
       UpperCamelCase__				=    batch_size
       UpperCamelCase__				=    image_size
       UpperCamelCase__				=    patch_sizes
       UpperCamelCase__				=    patch_stride
       UpperCamelCase__				=    patch_padding
       UpperCamelCase__				=    is_training
       UpperCamelCase__				=    use_labels
       UpperCamelCase__				=    num_labels
       UpperCamelCase__				=    num_channels
       UpperCamelCase__				=    embed_dim
       UpperCamelCase__				=    num_heads
       UpperCamelCase__				=    stride_kv
       UpperCamelCase__				=    depth
       UpperCamelCase__				=    cls_token
       UpperCamelCase__				=    attention_drop_rate
       UpperCamelCase__				=    initializer_range
       UpperCamelCase__				=    layer_norm_eps







  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.num_labels						)

       UpperCamelCase__				=    self.get_config()
       return config, pixel_values, labels







  def 	UpperCAmelCase_ (self						):
       return CvtConfig(
           image_size=self.image_size	,      num_labels=self.num_labels	,      num_channels=self.num_channels	,      embed_dim=self.embed_dim	,      num_heads=self.num_heads	,      patch_sizes=self.patch_sizes	,      patch_padding=self.patch_padding	,      patch_stride=self.patch_stride	,      stride_kv=self.stride_kv	,      depth=self.depth	,      cls_token=self.cls_token	,      attention_drop_rate=self.attention_drop_rate	,      initializer_range=self.initializer_range	,      )







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    CvtModel(config=SCREAMING_SNAKE_CASE_						)
       model.to(SCREAMING_SNAKE_CASE_						)
       model.eval()
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_						)
       UpperCamelCase__				=    (self.image_size, self.image_size)
       UpperCamelCase__		,	UpperCamelCase__				=    image_size[0], image_size[1]
       for i in range(len(self.depth						)						):
            UpperCamelCase__				=    floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
            UpperCamelCase__				=    floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1						)
       self.parent.assertEqual(result.last_hidden_state.shape	,      (self.batch_size, self.embed_dim[-1], height, width)						)







  def 	UpperCAmelCase_ (self	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
       UpperCamelCase__				=    self.num_labels
       UpperCamelCase__				=    CvtForImageClassification(SCREAMING_SNAKE_CASE_						)
       model.to(SCREAMING_SNAKE_CASE_						)
       model.eval()
       UpperCamelCase__				=    model(SCREAMING_SNAKE_CASE_	,      labels=SCREAMING_SNAKE_CASE_						)
       self.parent.assertEqual(result.logits.shape	,      (self.batch_size, self.num_labels)						)







  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_torch
class      __A(    __snake_case    ,				__snake_case    ,				unittest.TestCase			):

  """simple docstring"""
  SCREAMING_SNAKE_CASE__         =      (CvtModel, CvtForImageClassification) if is_torch_available() else ()
  SCREAMING_SNAKE_CASE__         =      (
      {'feature-extraction': CvtModel, 'image-classification': CvtForImageClassification}
      if is_torch_available()
      else {}
  )

  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False
  SCREAMING_SNAKE_CASE__         =      False







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    CvtModelTester(self						)
       UpperCamelCase__				=    ConfigTester(self	,      config_class=SCREAMING_SNAKE_CASE_	,      has_text_modality=SCREAMING_SNAKE_CASE_	,      hidden_size=37						)







  def 	UpperCAmelCase_ (self						):
       self.create_and_test_config_common_properties()
       self.config_tester.create_and_test_config_to_json_string()
       self.config_tester.create_and_test_config_to_json_file()
       self.config_tester.create_and_test_config_from_and_save_pretrained()
       self.config_tester.create_and_test_config_with_num_labels()
       self.config_tester.check_config_can_be_init_without_params()
       self.config_tester.check_config_arguments_init()







  def 	UpperCAmelCase_ (self						):
       return







  @unittest.skip(reason="""Cvt does not output attentions"""						)
  def 	UpperCAmelCase_ (self						):
       pass







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







  @unittest.skip(reason="""Cvt does not support input and output embeddings"""						)
  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(SCREAMING_SNAKE_CASE_						)
            UpperCamelCase__				=    inspect.signature(model.forward						)
            # signature.parameters is an OrderedDict => so arg_names order is deterministic
            UpperCamelCase__				=    [*signature.parameters.keys()]

            UpperCamelCase__				=    ["""pixel_values"""]
            self.assertListEqual(arg_names[:1]	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       def check_hidden_states_output(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						):
            UpperCamelCase__				=    model_class(SCREAMING_SNAKE_CASE_						)
            model.to(SCREAMING_SNAKE_CASE_						)
            model.eval()

            with torch.no_grad():
                 UpperCamelCase__				=    model(**self._prepare_for_class(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)						)

            UpperCamelCase__				=    outputs.hidden_states

            UpperCamelCase__				=    len(self.model_tester.depth						)
            self.assertEqual(len(SCREAMING_SNAKE_CASE_						)	,      SCREAMING_SNAKE_CASE_						)

            # verify the first hidden states (first block)
            self.assertListEqual(
                list(hidden_states[0].shape[-3:]						)	,      [
                    self.model_tester.embed_dim[0],
                    self.model_tester.image_size // 4,
                    self.model_tester.image_size // 4,
                ]	,      )

       UpperCamelCase__		,	UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
            UpperCamelCase__				=    True
            check_hidden_states_output(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)

            # check that output_hidden_states also work using config
            del inputs_dict["output_hidden_states"]
            UpperCamelCase__				=    True

            check_hidden_states_output(SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_	,      SCREAMING_SNAKE_CASE_						)







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_						)







  @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
  def 	UpperCAmelCase_ (self						):
       pass







  @slow
  def 	UpperCAmelCase_ (self						):
       for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
            UpperCamelCase__				=    CvtModel.from_pretrained(SCREAMING_SNAKE_CASE_						)
            self.assertIsNotNone(SCREAMING_SNAKE_CASE_						)






def 						__magic_name__			(   ):



     '''simple docstring'''




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




@require_torch
@require_vision
class      __A(    unittest.TestCase			):

  """simple docstring"""







  @cached_property
  def 	UpperCAmelCase_ (self						):
       return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)







  @slow
  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(SCREAMING_SNAKE_CASE_						)

       UpperCamelCase__				=    self.default_image_processor
       UpperCamelCase__				=    prepare_img()
       UpperCamelCase__				=    image_processor(images=SCREAMING_SNAKE_CASE_	,      return_tensors="""pt"""						).to(SCREAMING_SNAKE_CASE_						)

       # forward pass
       with torch.no_grad():
            UpperCamelCase__				=    model(**SCREAMING_SNAKE_CASE_						)

       # verify the logits
       UpperCamelCase__				=    torch.Size((1, 10_00)						)
       self.assertEqual(outputs.logits.shape	,      SCREAMING_SNAKE_CASE_						)

       UpperCamelCase__				=    torch.tensor([0.9285, 0.9015, -0.3150]						).to(SCREAMING_SNAKE_CASE_						)

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







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


lowerCamelCase_						     =					['''text''', '''image''', '''audio''']






def 						__magic_name__			(   __a      :	List[str]						):



     '''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(3_000						)						)
          elif isinstance(__a	,		__a						):
               inputs.append(create_inputs(__a						)						)
          else:
               raise ValueError(f"Invalid type requested: {input_type}"						)

     return inputs






def 						__magic_name__			(   __a      :	List						):



     '''simple docstring'''




     UpperCamelCase__				=    []

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

     return output_types




@is_tool_test
class      __A:

  """simple docstring"""







  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	,      SCREAMING_SNAKE_CASE_						):
                 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(*SCREAMING_SNAKE_CASE_						)

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

       self.assertListEqual(output_types(SCREAMING_SNAKE_CASE_						)	,      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(*SCREAMING_SNAKE_CASE_						)

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

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

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







  def 	UpperCAmelCase_ (self						):
       UpperCamelCase__				=    create_inputs(self.tool.inputs						)

       UpperCamelCase__				=    []

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

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

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





