
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
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 TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
      from PIL import Image

      from transformers import ConvNextImageProcessor





class 							A__		:
      def __init__(				self   ,  __magic_name__   ,  __magic_name__=1_3   ,  __magic_name__=3_2   ,  __magic_name__=3   ,  __magic_name__=4   ,  __magic_name__=[1_0, 2_0, 3_0, 4_0]   ,  __magic_name__=[2, 2, 3, 2]   ,  __magic_name__=True   ,  __magic_name__=True   ,  __magic_name__=3_7   ,  __magic_name__="gelu"   ,  __magic_name__=1_0   ,  __magic_name__=0.02   ,  __magic_name__=3   ,  __magic_name__=None   ,  ):
       lowerCamelCase		:     List[str]          =				parent
       lowerCamelCase		:     Any          =				batch_size
       lowerCamelCase		:     Optional[Any]          =				image_size
       lowerCamelCase		:     str          =				num_channels
       lowerCamelCase		:     Optional[int]          =				num_stages
       lowerCamelCase		:     Any          =				hidden_sizes
       lowerCamelCase		:     int          =				depths
       lowerCamelCase		:     int          =				is_training
       lowerCamelCase		:     int          =				use_labels
       lowerCamelCase		:     Union[str, Any]          =				intermediate_size
       lowerCamelCase		:     Optional[int]          =				hidden_act
       lowerCamelCase		:     List[str]          =				type_sequence_label_size
       lowerCamelCase		:     List[Any]          =				initializer_range
       lowerCamelCase		:     Any          =				scope
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     str          =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]				)

       lowerCamelCase		:     List[str]          =				None
       if self.use_labels:
        lowerCamelCase		:     Union[str, Any]          =				ids_tensor([self.batch_size]   ,  self.type_sequence_label_size				)

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

       return config, pixel_values, labels
      def 						UpperCamelCase__							(				self				):
       return ConvNextConfig(
           num_channels=self.num_channels   ,  hidden_sizes=self.hidden_sizes   ,  depths=self.depths   ,  num_stages=self.num_stages   ,  hidden_act=self.hidden_act   ,  is_decoder=_UpperCAmelCase   ,  initializer_range=self.initializer_range   ,  )
      def 						UpperCamelCase__							(				self   ,  __magic_name__   ,  __magic_name__   ,  __magic_name__				):
       lowerCamelCase		:     Union[str, Any]          =				TFConvNextModel(config=_UpperCAmelCase				)
       lowerCamelCase		:     Optional[Any]          =				model(_UpperCAmelCase   ,  training=_UpperCAmelCase				)
       # 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 // 3_2, self.image_size // 3_2)   ,  )
      def 						UpperCamelCase__							(				self   ,  __magic_name__   ,  __magic_name__   ,  __magic_name__				):
       lowerCamelCase		:     int          =				self.type_sequence_label_size
       lowerCamelCase		:     str          =				TFConvNextForImageClassification(_UpperCAmelCase				)
       lowerCamelCase		:     Any          =				model(_UpperCAmelCase   ,  labels=_UpperCAmelCase   ,  training=_UpperCAmelCase				)
       self.parent.assertEqual(result.logits.shape   ,  (self.batch_size, self.type_sequence_label_size)				)






      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Optional[int]          =				self.prepare_config_and_inputs()
       lowerCamelCase      ,   lowerCamelCase      ,   lowerCamelCase		:     Optional[Any]          =				config_and_inputs
       lowerCamelCase		:     Dict          =				{"""pixel_values""": pixel_values}
       return config, inputs_dict





@require_tf
class 							A__		(     lowerCAmelCase__  ,       lowerCAmelCase__  ,       unittest.TestCase):
      _UpperCAmelCase    :   List[Any]   	=      (TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
      _UpperCAmelCase    :   List[Any]   	=      (
          {"feature-extraction": TFConvNextModel, "image-classification": TFConvNextForImageClassification}
          if is_tf_available()
          else {}
      )

      _UpperCAmelCase    :   Union[str, Any]   	=      False
      _UpperCAmelCase    :   Union[str, Any]   	=      False
      _UpperCAmelCase    :   Any   	=      False
      _UpperCAmelCase    :   Optional[Any]   	=      False
      _UpperCAmelCase    :   Optional[int]   	=      False
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Optional[int]          =				TFConvNextModelTester(self				)
       lowerCamelCase		:     Optional[int]          =				ConfigTester(
           self   ,  config_class=_UpperCAmelCase   ,  has_text_modality=_UpperCAmelCase   ,  hidden_size=3_7   ,  )
      @unittest.skip(reason="""ConvNext does not use inputs_embeds"""				)
      def 						UpperCamelCase__							(				self				):
       pass
      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""				)				) == 0   ,  reason="""TF does not support backprop for grouped convolutions on CPU."""   ,  )
      @slow
      def 						UpperCamelCase__							(				self				):
       super().test_keras_fit()
      @unittest.skip(reason="""ConvNext does not support input and output embeddings"""				)
      def 						UpperCamelCase__							(				self				):
       pass
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     List[Any]          =				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase		:     str          =				model_class(_UpperCAmelCase				)
        lowerCamelCase		:     int          =				inspect.signature(model.call				)
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        lowerCamelCase		:     Union[str, Any]          =				[*signature.parameters.keys()]

        lowerCamelCase		:     List[str]          =				["""pixel_values"""]
        self.assertListEqual(arg_names[:1]   ,  _UpperCAmelCase				)
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     List[str]          =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase				)
      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices("""GPU"""				)				) == 0   ,  reason="""TF does not support backprop for grouped convolutions on CPU."""   ,  )
      def 						UpperCamelCase__							(				self				):
       super().test_dataset_conversion()
      def 						UpperCamelCase__							(				self				):


       def check_hidden_states_output(__magic_name__   ,  __magic_name__   ,  __magic_name__				):
        lowerCamelCase		:     int          =				model_class(_UpperCAmelCase				)

        lowerCamelCase		:     int          =				model(**self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase				)				)
        lowerCamelCase		:     Optional[int]          =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

        lowerCamelCase		:     Union[str, Any]          =				self.model_tester.num_stages
        self.assertEqual(len(_UpperCAmelCase				)   ,  expected_num_stages + 1				)

        # ConvNext'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		:     str          =				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        lowerCamelCase		:     Optional[int]          =				True
        check_hidden_states_output(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase				)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        lowerCamelCase		:     Dict          =				True

        check_hidden_states_output(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase				)
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase      ,   lowerCamelCase		:     Dict          =				self.model_tester.prepare_config_and_inputs_for_common()

       def check_equivalence(__magic_name__   ,  __magic_name__   ,  __magic_name__   ,  __magic_name__={}				):
        lowerCamelCase		:     Union[str, Any]          =				model(_UpperCAmelCase   ,  return_dict=_UpperCAmelCase   ,  **_UpperCAmelCase				)
        lowerCamelCase		:     Union[str, Any]          =				model(_UpperCAmelCase   ,  return_dict=_UpperCAmelCase   ,  **_UpperCAmelCase				).to_tuple()

        def recursive_check(__magic_name__   ,  __magic_name__				):
         if isinstance(_UpperCAmelCase   ,  (List, Tuple)				):
          for tuple_iterable_value, dict_iterable_value in zip(_UpperCAmelCase   ,  _UpperCAmelCase				):
           recursive_check(_UpperCAmelCase   ,  _UpperCAmelCase				)
         elif tuple_object is None:
          return
         else:
          self.assertTrue(
              all(tf.equal(_UpperCAmelCase   ,  _UpperCAmelCase				)				)   ,  msg=(
                  """Tuple and dict output are not equal. Difference:"""
                  F''' {tf.math.reduce_max(tf.abs(tuple_object - dict_object				)				)}'''
              )   ,  )

         recursive_check(_UpperCAmelCase   ,  _UpperCAmelCase				)

       for model_class in self.all_model_classes:
        lowerCamelCase		:     Tuple          =				model_class(_UpperCAmelCase				)

        lowerCamelCase		:     List[str]          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase				)
        lowerCamelCase		:     List[Any]          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase				)
        check_equivalence(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase				)

        lowerCamelCase		:     Any          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase   ,  return_labels=_UpperCAmelCase				)
        lowerCamelCase		:     Any          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase   ,  return_labels=_UpperCAmelCase				)
        check_equivalence(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase				)

        lowerCamelCase		:     Any          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase				)
        lowerCamelCase		:     List[Any]          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase				)
        check_equivalence(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase   ,  {"""output_hidden_states""": True}				)

        lowerCamelCase		:     List[str]          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase   ,  return_labels=_UpperCAmelCase				)
        lowerCamelCase		:     List[Any]          =				self._prepare_for_class(_UpperCAmelCase   ,  _UpperCAmelCase   ,  return_labels=_UpperCAmelCase				)
        check_equivalence(_UpperCAmelCase   ,  _UpperCAmelCase   ,  _UpperCAmelCase   ,  {"""output_hidden_states""": True}				)
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     int          =				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase				)






      @slow
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     Optional[Any]          =				TFConvNextModel.from_pretrained("""facebook/convnext-tiny-224"""				)
       self.assertIsNotNone(_UpperCAmelCase				)





def    _a (						):
 lowerCamelCase		:     List[Any]          =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
 return image





@require_tf
@require_vision
class 							A__		(     unittest.TestCase):
      @cached_property
      def 						UpperCamelCase__							(				self				):
       return ConvNextImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""				) if is_vision_available() else None






      @slow
      def 						UpperCamelCase__							(				self				):
       lowerCamelCase		:     List[str]          =				TFConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""				)

       lowerCamelCase		:     List[str]          =				self.default_image_processor
       lowerCamelCase		:     Optional[Any]          =				prepare_img()
       lowerCamelCase		:     Tuple          =				image_processor(images=_UpperCAmelCase   ,  return_tensors="""tf"""				)

       # forward pass
       lowerCamelCase		:     int          =				model(**_UpperCAmelCase				)

       # verify the logits
       lowerCamelCase		:     Union[str, Any]          =				tf.TensorShape((1, 1_0_0_0)				)
       self.assertEqual(outputs.logits.shape   ,  _UpperCAmelCase				)

       lowerCamelCase		:     Any          =				tf.constant([-0.0_260, -0.4_739, 0.1_911]				)

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






# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
    is_vision_available,
)


_lowerCamelCase        ={
    """configuration_tvlt""": ["""TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP""", """TvltConfig"""],
    """feature_extraction_tvlt""": ["""TvltFeatureExtractor"""],
    """processing_tvlt""": ["""TvltProcessor"""],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase        =[
          """TVLT_PRETRAINED_MODEL_ARCHIVE_LIST""",
          """TvltModel""",
          """TvltForPreTraining""",
          """TvltForAudioVisualClassification""",
          """TvltPreTrainedModel""",
      ]

try:
      if not is_vision_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      _lowerCamelCase        =["""TvltImageProcessor"""]


if TYPE_CHECKING:
      from .configuration_tvlt import TVLT_PRETRAINED_CONFIG_ARCHIVE_MAP, TvltConfig
      from .processing_tvlt import TvltProcessor
      from .feature_extraction_tvlt import TvltFeatureExtractor

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_tvlt import (
                TVLT_PRETRAINED_MODEL_ARCHIVE_LIST,
                TvltForAudioVisualClassification,
                TvltForPreTraining,
                TvltModel,
                TvltPreTrainedModel,
            )

      try:
            if not is_vision_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .image_processing_tvlt import TvltImageProcessor


else:
      import sys

      _lowerCamelCase        =_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




