




from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
     from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor





class 			__lowerCamelCase	:




    """simple docstring"""

    def __init__(	self					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]=3       ,     SCREAMING_SNAKE_CASE__					:					List[str]=32       ,     SCREAMING_SNAKE_CASE__					:					List[str]=3       ,     SCREAMING_SNAKE_CASE__					:					str=10       ,     SCREAMING_SNAKE_CASE__					:					str=[10, 20, 30, 40]       ,     SCREAMING_SNAKE_CASE__					:					str=[1, 1, 2, 1]       ,     SCREAMING_SNAKE_CASE__					:					int=True       ,     SCREAMING_SNAKE_CASE__					:					Tuple=True       ,     SCREAMING_SNAKE_CASE__					:					List[Any]="relu"       ,     SCREAMING_SNAKE_CASE__					:					Any=3       ,     SCREAMING_SNAKE_CASE__					:					Tuple=None       ,     )				->	Any:
      lowerCAmelCase__          =			parent
      lowerCAmelCase__          =			batch_size
      lowerCAmelCase__          =			image_size
      lowerCAmelCase__          =			num_channels
      lowerCAmelCase__          =			embeddings_size
      lowerCAmelCase__          =			hidden_sizes
      lowerCAmelCase__          =			depths
      lowerCAmelCase__          =			is_training
      lowerCAmelCase__          =			use_labels
      lowerCAmelCase__          =			hidden_act
      lowerCAmelCase__          =			num_labels
      lowerCAmelCase__          =			scope
      lowerCAmelCase__          =			len(_a       )


    def        a				(	self					:					Union[str, Any]       )				->	str:
      lowerCAmelCase__          =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

      lowerCAmelCase__          =			None
      if self.use_labels:
        lowerCAmelCase__          =			ids_tensor([self.batch_size]       ,     self.num_labels       )

      lowerCAmelCase__          =			self.get_config()

      return config, pixel_values, labels


    def        a				(	self					:					Optional[Any]       )				->	Any:
      return ResNetConfig(
          num_channels=self.num_channels       ,     embeddings_size=self.embeddings_size       ,     hidden_sizes=self.hidden_sizes       ,     depths=self.depths       ,     hidden_act=self.hidden_act       ,     num_labels=self.num_labels       ,     image_size=self.image_size       ,     )


    def        a				(	self					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					Union[str, Any]       ,     SCREAMING_SNAKE_CASE__					:					Any       ,     SCREAMING_SNAKE_CASE__					:					List[str]       )				->	int:
      lowerCAmelCase__          =			TFResNetModel(config=_a       )
      lowerCAmelCase__          =			model(_a       )
      # expected last hidden states: B, C, H // 32, W // 32
      self.parent.assertEqual(
          result.last_hidden_state.shape       ,     (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,     )


    def        a				(	self					:					str       ,     SCREAMING_SNAKE_CASE__					:					Tuple       ,     SCREAMING_SNAKE_CASE__					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					Dict       )				->	int:
      lowerCAmelCase__          =			self.num_labels
      lowerCAmelCase__          =			TFResNetForImageClassification(_a       )
      lowerCAmelCase__          =			model(_a       ,     labels=_a       )
      self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.num_labels)       )


    def        a				(	self					:					Dict       )				->	Tuple:
      lowerCAmelCase__          =			self.prepare_config_and_inputs()
      lowerCAmelCase__     ,		lowerCAmelCase__     ,		lowerCAmelCase__          =			config_and_inputs
      lowerCAmelCase__          =			{"pixel_values": pixel_values}
      return config, inputs_dict






@require_tf
class 			__lowerCamelCase	(   UpperCamelCase__     ,    UpperCamelCase__     ,    unittest.TestCase   ):




    """simple docstring"""

    snake_case__ =				(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
    snake_case__ =				(
        {'''feature-extraction''': TFResNetModel, '''image-classification''': TFResNetForImageClassification}
        if is_tf_available()
        else {}
    )

    snake_case__ =				False
    snake_case__ =				False
    snake_case__ =				False
    snake_case__ =				False
    snake_case__ =				False


    def        a				(	self					:					int       )				->	Any:
      lowerCAmelCase__          =			TFResNetModelTester(self       )
      lowerCAmelCase__          =			ConfigTester(self       ,     config_class=_a       ,     has_text_modality=_a       )


    def        a				(	self					:					List[Any]       )				->	Tuple:
      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        a				(	self					:					Optional[int]       )				->	Tuple:
      return


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


    @unittest.skip(reason="ResNet does not support input and output embeddings"       )
    def        a				(	self					:					Optional[int]       )				->	Dict:
      pass


    def        a				(	self					:					Dict       )				->	Any:
      lowerCAmelCase__     ,		lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs_for_common()

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

        lowerCAmelCase__          =			["pixel_values"]
        self.assertListEqual(arg_names[:1]       ,     _a       )


    def        a				(	self					:					List[str]       )				->	Any:
      lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_a       )


    def        a				(	self					:					int       )				->	Optional[Any]:
      def check_hidden_states_output(SCREAMING_SNAKE_CASE__					:					str       ,     SCREAMING_SNAKE_CASE__					:					Optional[Any]       ,     SCREAMING_SNAKE_CASE__					:					List[Any]       ):
        lowerCAmelCase__          =			model_class(_a       )
        lowerCAmelCase__          =			model(**self._prepare_for_class(_a       ,     _a       )       )

        lowerCAmelCase__          =			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        lowerCAmelCase__          =			self.model_tester.num_stages
        self.assertEqual(len(_a       )       ,     expected_num_stages + 1       )

        # ResNet's feature maps are of shape (batch_size, num_channels, height, width)
        self.assertListEqual(
            list(hidden_states[0].shape[-2:]       )       ,     [self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,     )

      lowerCAmelCase__     ,		lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs_for_common()
      lowerCAmelCase__          =			["basic", "bottleneck"]
      for model_class in self.all_model_classes:
        for layer_type in layers_type:
          lowerCAmelCase__          =			layer_type
          lowerCAmelCase__          =			True
          check_hidden_states_output(_a       ,     _a       ,     _a       )

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

          check_hidden_states_output(_a       ,     _a       ,     _a       )


    def        a				(	self					:					Tuple       )				->	Dict:
      lowerCAmelCase__          =			self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_a       )


    @slow
    def        a				(	self					:					Optional[int]       )				->	List[Any]:
      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        lowerCAmelCase__          =			TFResNetModel.from_pretrained(_a       )
        self.assertIsNotNone(_a       )






def 							_A       (						):
  """simple docstring"""

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






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




    """simple docstring"""

    @cached_property
    def        a				(	self					:					Tuple       )				->	Any:
      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
          if is_vision_available()
          else None
      )


    @slow
    def        a				(	self					:					Optional[Any]       )				->	str:
      lowerCAmelCase__          =			TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

      lowerCAmelCase__          =			self.default_image_processor
      lowerCAmelCase__          =			prepare_img()
      lowerCAmelCase__          =			image_processor(images=_a       ,     return_tensors="tf"       )

      # forward pass
      lowerCAmelCase__          =			model(**_a       )

      # verify the logits
      lowerCAmelCase__          =			tf.TensorShape((1, 1_000)       )
      self.assertEqual(outputs.logits.shape       ,     _a       )

      lowerCAmelCase__          =			tf.constant([-11.1_069, -9.7_877, -8.3_777]       )

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






import warnings
from contextlib import contextmanager

from ...processing_utils import ProcessorMixin





class 			__lowerCamelCase	(   UpperCamelCase__   ):




    """simple docstring"""

    snake_case__ =				"Speech2TextFeatureExtractor"
    snake_case__ =				"Speech2TextTokenizer"


    def __init__(	self					:					int       ,     SCREAMING_SNAKE_CASE__					:					Dict       ,     SCREAMING_SNAKE_CASE__					:					Tuple       )				->	Optional[Any]:
         super().__init__(SCREAMING_SNAKE_CASE__       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False


    def __call__(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					int       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Optional[Any]:
         # For backward compatibility
         if self._in_target_context_manager:
              return self.current_processor(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if "raw_speech" in kwargs:
              warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead."       )
              lowerCAmelCase__          =			kwargs.pop("raw_speech"       )
         else:
              lowerCAmelCase__          =			kwargs.pop("audio"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("sampling_rate"       ,     SCREAMING_SNAKE_CASE__       )
         lowerCAmelCase__          =			kwargs.pop("text"       ,     SCREAMING_SNAKE_CASE__       )
         if len(SCREAMING_SNAKE_CASE__       ) > 0:
              lowerCAmelCase__          =			args[0]
              lowerCAmelCase__          =			args[1:]

         if audio is None and text is None:
              raise ValueError("You need to specify either an `audio` or `text` input to process."       )

         if audio is not None:
              lowerCAmelCase__          =			self.feature_extractor(SCREAMING_SNAKE_CASE__       ,     *SCREAMING_SNAKE_CASE__       ,     sampling_rate=SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )
         if text is not None:
              lowerCAmelCase__          =			self.tokenizer(SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )

         if text is None:
              return inputs
         elif audio is None:
              return encodings
         else:
              lowerCAmelCase__          =			encodings["input_ids"]
              return inputs


    def        a				(	self					:					str       ,     *SCREAMING_SNAKE_CASE__					:					Dict       ,     **SCREAMING_SNAKE_CASE__					:					int       )				->	Union[str, Any]:
         return self.tokenizer.batch_decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    def        a				(	self					:					Dict       ,     *SCREAMING_SNAKE_CASE__					:					Optional[int]       ,     **SCREAMING_SNAKE_CASE__					:					Optional[int]       )				->	Optional[Any]:
         return self.tokenizer.decode(*SCREAMING_SNAKE_CASE__       ,     **SCREAMING_SNAKE_CASE__       )


    @contextmanager
    def        a				(	self					:					Union[str, Any]       )				->	Any:
         warnings.warn(
             "`as_target_processor` is deprecated and will be removed in v5 of Transformers. You can process your "
             "labels by using the argument `text` of the regular `__call__` method (either in the same call as "
             "your audio inputs, or in a separate call."       )
         lowerCAmelCase__          =			True
         lowerCAmelCase__          =			self.tokenizer
         yield
         lowerCAmelCase__          =			self.feature_extractor
         lowerCAmelCase__          =			False
