






from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import SwinConfig
from transformers.testing_utils import require_tf, require_vision, slow, to_atuple
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.models.swin.modeling_tf_swin import (
      TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFSwinForImageClassification,
      TFSwinForMaskedImageModeling,
      TFSwinModel,
  )


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor






class 	lowercase_      :






      '''simple docstring'''




      def __init__(   self   :		Optional[int]				,      __UpperCAmelCase   :		List[str]				,      __UpperCAmelCase   :		str=13				,      __UpperCAmelCase   :		int=32				,      __UpperCAmelCase   :		Optional[int]=2				,      __UpperCAmelCase   :		Dict=3				,      __UpperCAmelCase   :		str=16				,      __UpperCAmelCase   :		int=[1, 2, 1]				,      __UpperCAmelCase   :		Tuple=[2, 2, 4]				,      __UpperCAmelCase   :		str=2				,      __UpperCAmelCase   :		Dict=2.0				,      __UpperCAmelCase   :		int=True				,      __UpperCAmelCase   :		str=0.0				,      __UpperCAmelCase   :		Any=0.0				,      __UpperCAmelCase   :		Tuple=0.1				,      __UpperCAmelCase   :		str="gelu"				,      __UpperCAmelCase   :		Optional[Any]=False				,      __UpperCAmelCase   :		List[str]=True				,      __UpperCAmelCase   :		List[Any]=0.02				,      __UpperCAmelCase   :		Union[str, Any]=1e-5				,      __UpperCAmelCase   :		str=True				,      __UpperCAmelCase   :		Dict=None				,      __UpperCAmelCase   :		str=True				,      __UpperCAmelCase   :		List[str]=10				,      __UpperCAmelCase   :		str=8				,      )					->List[str]:




       """simple docstring"""


       a							=   parent
       a							=   batch_size
       a							=   image_size
       a							=   patch_size
       a							=   num_channels
       a							=   embed_dim
       a							=   depths
       a							=   num_heads
       a							=   window_size
       a							=   mlp_ratio
       a							=   qkv_bias
       a							=   hidden_dropout_prob
       a							=   attention_probs_dropout_prob
       a							=   drop_path_rate
       a							=   hidden_act
       a							=   use_absolute_embeddings
       a							=   patch_norm
       a							=   layer_norm_eps
       a							=   initializer_range
       a							=   is_training
       a							=   scope
       a							=   use_labels
       a							=   type_sequence_label_size
       a							=   encoder_stride







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




       """simple docstring"""


       a							=   floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

       a							=   self.get_config()

       return config, pixel_values, labels







      def    __lowerCAmelCase      (   self   :		Optional[Any]						)					->Union[str, Any]:




       """simple docstring"""


       return SwinConfig(
           image_size=self.image_size				,      patch_size=self.patch_size				,      num_channels=self.num_channels				,      embed_dim=self.embed_dim				,      depths=self.depths				,      num_heads=self.num_heads				,      window_size=self.window_size				,      mlp_ratio=self.mlp_ratio				,      qkv_bias=self.qkv_bias				,      hidden_dropout_prob=self.hidden_dropout_prob				,      attention_probs_dropout_prob=self.attention_probs_dropout_prob				,      drop_path_rate=self.drop_path_rate				,      hidden_act=self.hidden_act				,      use_absolute_embeddings=self.use_absolute_embeddings				,      path_norm=self.patch_norm				,      layer_norm_eps=self.layer_norm_eps				,      initializer_range=self.initializer_range				,      encoder_stride=self.encoder_stride				,      )







      def    __lowerCAmelCase      (   self   :		List[Any]				,      __UpperCAmelCase   :		List[Any]				,      __UpperCAmelCase   :		Dict				,      __UpperCAmelCase   :		List[str]						)					->Union[str, Any]:




       """simple docstring"""


       a							=   TFSwinModel(config=UpperCAmelCase_						)
       a							=   model(UpperCAmelCase_						)

       a							=   ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths						) - 1))
       a							=   int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

       self.parent.assertEqual(result.last_hidden_state.shape				,      (self.batch_size, expected_seq_len, expected_dim)						)







      def    __lowerCAmelCase      (   self   :		Dict				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		List[str]						)					->Optional[int]:




       """simple docstring"""


       a							=   TFSwinForMaskedImageModeling(config=UpperCAmelCase_						)
       a							=   model(UpperCAmelCase_						)
       self.parent.assertEqual(
           result.logits.shape				,      (self.batch_size, self.num_channels, self.image_size, self.image_size)						)

       # test greyscale images
       a							=   1
       a							=   TFSwinForMaskedImageModeling(UpperCAmelCase_						)

       a							=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       a							=   model(UpperCAmelCase_						)
       self.parent.assertEqual(result.logits.shape				,      (self.batch_size, 1, self.image_size, self.image_size)						)







      def    __lowerCAmelCase      (   self   :		Tuple				,      __UpperCAmelCase   :		str				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		str						)					->Union[str, Any]:




       """simple docstring"""


       a							=   self.type_sequence_label_size
       a							=   TFSwinForImageClassification(UpperCAmelCase_						)
       a							=   model(UpperCAmelCase_				,      labels=UpperCAmelCase_						)
       self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.type_sequence_label_size)						)

       # test greyscale images
       a							=   1
       a							=   TFSwinForImageClassification(UpperCAmelCase_						)
       a							=   floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
       a							=   model(UpperCAmelCase_						)
       self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.type_sequence_label_size)						)







      def    __lowerCAmelCase      (   self   :		Dict						)					->List[str]:




       """simple docstring"""


       a							=   self.prepare_config_and_inputs()
       a							=   config_and_inputs
       a							=   {'pixel_values': pixel_values}
       return config, inputs_dict






@require_tf
class 	lowercase_      (			lowercase				,						lowercase				,						unittest.TestCase     ):






      '''simple docstring'''




      __snake_case  						=						(
          (
              TFSwinModel,
              TFSwinForImageClassification,
              TFSwinForMaskedImageModeling,
          )
          if is_tf_available()
          else ()
      )
      __snake_case  						=						(
          {"feature-extraction": TFSwinModel, "image-classification": TFSwinForImageClassification}
          if is_tf_available()
          else {}
      )

      __snake_case  						=						False
      __snake_case  						=						False
      __snake_case  						=						False
      __snake_case  						=						False







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




       """simple docstring"""


       a							=   TFSwinModelTester(self						)
       a							=   ConfigTester(self				,      config_class=UpperCAmelCase_				,      embed_dim=37						)







      def    __lowerCAmelCase      (   self   :		Union[str, Any]						)					->Optional[int]:




       """simple docstring"""


       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    __lowerCAmelCase      (   self   :		Tuple						)					->Tuple:




       """simple docstring"""


       return







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




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*UpperCAmelCase_						)







      def    __lowerCAmelCase      (   self   :		Union[str, Any]						)					->Optional[Any]:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase_						)







      def    __lowerCAmelCase      (   self   :		int						)					->Dict:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_						)







      @unittest.skip(reason='''Swin does not use inputs_embeds'''						)
      def    __lowerCAmelCase      (   self   :		List[Any]						)					->Union[str, Any]:




       """simple docstring"""


       pass







      def    __lowerCAmelCase      (   self   :		Any						)					->Optional[int]:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
        a							=   model_class(UpperCAmelCase_						)
        self.assertIsInstance(model.get_input_embeddings()				,      tf.keras.layers.Layer						)
        a							=   model.get_output_embeddings()
        self.assertTrue(x is None or isinstance(UpperCAmelCase_				,      tf.keras.layers.Dense						)						)







      def    __lowerCAmelCase      (   self   :		Optional[int]						)					->Optional[Any]:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

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

        a							=   ['pixel_values']
        self.assertListEqual(arg_names[:1]				,      UpperCAmelCase_						)







      def    __lowerCAmelCase      (   self   :		Dict						)					->str:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()
       a							=   True

       for model_class in self.all_model_classes:
        a							=   True
        a							=   False
        a							=   True
        a							=   model_class(UpperCAmelCase_						)
        a							=   model(**self._prepare_for_class(UpperCAmelCase_				,      UpperCAmelCase_						)						)
        a							=   outputs.attentions
        a							=   len(self.model_tester.depths						)
        self.assertEqual(len(UpperCAmelCase_						)				,      UpperCAmelCase_						)

        # check that output_attentions also work using config
        del inputs_dict["output_attentions"]
        a							=   True
        a							=   config.window_size**2
        a							=   model_class(UpperCAmelCase_						)
        a							=   model(**self._prepare_for_class(UpperCAmelCase_				,      UpperCAmelCase_						)						)
        a							=   outputs.attentions
        self.assertEqual(len(UpperCAmelCase_						)				,      UpperCAmelCase_						)

        self.assertListEqual(
            list(attentions[0].shape[-3:]						)				,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,      )
        a							=   len(UpperCAmelCase_						)

        # Check attention is always last and order is fine
        a							=   True
        a							=   True
        a							=   model_class(UpperCAmelCase_						)
        a							=   model(**self._prepare_for_class(UpperCAmelCase_				,      UpperCAmelCase_						)						)

        if hasattr(self.model_tester				,      '''num_hidden_states_types'''						):
         a							=   self.model_tester.num_hidden_states_types
        else:
         # also another +1 for reshaped_hidden_states
         a							=   2
        self.assertEqual(out_len + added_hidden_states				,      len(UpperCAmelCase_						)						)

        a							=   outputs.attentions

        self.assertEqual(len(UpperCAmelCase_						)				,      UpperCAmelCase_						)

        self.assertListEqual(
            list(self_attentions[0].shape[-3:]						)				,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]				,      )







      def    __lowerCAmelCase      (   self   :		Optional[Any]				,      __UpperCAmelCase   :		int				,      __UpperCAmelCase   :		Tuple				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		Union[str, Any]						)					->Any:




       """simple docstring"""


       a							=   model_class(UpperCAmelCase_						)
       a							=   model(**self._prepare_for_class(UpperCAmelCase_				,      UpperCAmelCase_						)						)
       a							=   outputs.hidden_states

       a							=   getattr(
           self.model_tester				,      '''expected_num_hidden_layers'''				,      len(self.model_tester.depths						) + 1						)
       self.assertEqual(len(UpperCAmelCase_						)				,      UpperCAmelCase_						)

       # Swin has a different seq_length
       a							=   to_atuple(config.patch_size						)

       a							=   (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

       self.assertListEqual(
           list(hidden_states[0].shape[-2:]						)				,      [num_patches, self.model_tester.embed_dim]				,      )

       a							=   outputs.reshaped_hidden_states
       self.assertEqual(len(UpperCAmelCase_						)				,      UpperCAmelCase_						)

       a							=   reshaped_hidden_states[0].shape

       a							=   tf.reshape(reshaped_hidden_states[0]				,      (batch_size, num_channels, height * width)						)
       a							=   tf.transpose(UpperCAmelCase_				,      (0, 2, 1)						)

       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:]						)				,      [num_patches, self.model_tester.embed_dim]				,      )







      def    __lowerCAmelCase      (   self   :		Optional[int]						)					->Tuple:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()

       a							=   to_atuple(self.model_tester.image_size						)

       for model_class in self.all_model_classes:
        a							=   True
        self.check_hidden_states_output(UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_						)

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

        self.check_hidden_states_output(UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_						)







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




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs_for_common()
       a							=   3

       a							=   to_atuple(self.model_tester.image_size						)
       a							=   to_atuple(config.patch_size						)

       a							=   image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
       a							=   image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

       for model_class in self.all_model_classes:
        a							=   True
        self.check_hidden_states_output(UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_				,      (padded_height, padded_width)						)

        # check that output_hidden_states also work using config
        del inputs_dict["output_hidden_states"]
        a							=   True
        self.check_hidden_states_output(UpperCAmelCase_				,      UpperCAmelCase_				,      UpperCAmelCase_				,      (padded_height, padded_width)						)







      @slow
      def    __lowerCAmelCase      (   self   :		Any						)					->int:




       """simple docstring"""


       for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a							=   TFSwinModel.from_pretrained(UpperCAmelCase_						)
        self.assertIsNotNone(UpperCAmelCase_						)






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






      '''simple docstring'''




      @cached_property
      def    __lowerCAmelCase      (   self   :		Dict						)					->Tuple:




       """simple docstring"""


       return (
           AutoImageProcessor.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''						)
           if is_vision_available()
           else None
       )







      @slow
      def    __lowerCAmelCase      (   self   :		Union[str, Any]						)					->int:




       """simple docstring"""


       a							=   TFSwinForImageClassification.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''						)
       a							=   self.default_image_processor

       a							=   Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''						)
       a							=   image_processor(images=UpperCAmelCase_				,      return_tensors='''tf'''						)

       # forward pass
       a							=   model(UpperCAmelCase_						)

       # verify the logits
       a							=   tf.TensorShape((1, 1_000)						)
       self.assertEqual(outputs.logits.shape				,      UpperCAmelCase_						)
       a							=   tf.constant([-0.0948, -0.6454, -0.0921]						)
       self.assertTrue(np.allclose(outputs.logits[0, :3]				,      UpperCAmelCase_				,      atol=1e-4						)						)










import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding






class 	lowercase_      (			lowercase     ):






      '''simple docstring'''




      __snake_case  						=						['''image_processor''', '''tokenizer''']
      __snake_case  						=						'''AutoImageProcessor'''
      __snake_case  						=						'''AutoTokenizer'''







      def __init__(   self   :		Any				,      __UpperCAmelCase   :		Union[str, Any]=None				,      __UpperCAmelCase   :		int=None				,      **__UpperCAmelCase   :		Union[str, Any]						)					->Dict:




       """simple docstring"""


       a							=   None
       if "feature_extractor" in kwargs:
        warnings.warn(
            '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
            ''' instead.'''				,      __UpperCAmelCase				,      )
        a							=   kwargs.pop('''feature_extractor'''						)

       a							=   image_processor if image_processor is not None else feature_extractor
       if image_processor is None:
        raise ValueError('''You have to specify an image_processor.'''						)
       if tokenizer is None:
        raise ValueError('''You have to specify a tokenizer.'''						)

       super().__init__(__UpperCAmelCase				,      __UpperCAmelCase						)
       a							=   self.image_processor







      def __call__(   self   :		List[Any]				,      __UpperCAmelCase   :		Optional[Any]=None				,      __UpperCAmelCase   :		Optional[int]=None				,      __UpperCAmelCase   :		str=None				,      **__UpperCAmelCase   :		List[Any]						)					->Dict:




       """simple docstring"""


       if text is None and images is None:
        raise ValueError('''You have to specify either text or images. Both cannot be none.'''						)

       if text is not None:
        a							=   self.tokenizer(__UpperCAmelCase				,      return_tensors=__UpperCAmelCase				,      **__UpperCAmelCase						)

       if images is not None:
        a							=   self.image_processor(__UpperCAmelCase				,      return_tensors=__UpperCAmelCase				,      **__UpperCAmelCase						)

       if text is not None and images is not None:
        a							=   image_features.pixel_values
        return encoding
       elif text is not None:
        return encoding
       else:
        return BatchEncoding(data=dict(**__UpperCAmelCase						)				,      tensor_type=__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[Any]				,      *__UpperCAmelCase   :		Optional[Any]				,      **__UpperCAmelCase   :		List[str]						)					->Optional[Any]:




       """simple docstring"""


       return self.tokenizer.batch_decode(*__UpperCAmelCase				,      **__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		str				,      *__UpperCAmelCase   :		List[Any]				,      **__UpperCAmelCase   :		Optional[Any]						)					->Union[str, Any]:




       """simple docstring"""


       return self.tokenizer.decode(*__UpperCAmelCase				,      **__UpperCAmelCase						)







      @property
      def    __lowerCAmelCase      (   self   :		str						)					->str:




       """simple docstring"""


       a							=   self.tokenizer.model_input_names
       a							=   self.image_processor.model_input_names
       return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names						)						)







      @property
      def    __lowerCAmelCase      (   self   :		str						)					->Optional[Any]:




       """simple docstring"""


       warnings.warn(
           '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''				,      __UpperCAmelCase				,      )
       return self.image_processor_class







      @property
      def    __lowerCAmelCase      (   self   :		int						)					->Optional[Any]:




       """simple docstring"""


       warnings.warn(
           '''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.'''				,      __UpperCAmelCase				,      )
       return self.image_processor


