





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



      def __init__(					self     ,  lowercase_     ,  lowercase_=13     ,  lowercase_=32     ,  lowercase_=2     ,  lowercase_=3     ,  lowercase_=16     ,  lowercase_=[1, 2, 1]     ,  lowercase_=[2, 2, 4]     ,  lowercase_=2     ,  lowercase_=2.0     ,  lowercase_=True     ,  lowercase_=0.0     ,  lowercase_=0.0     ,  lowercase_=0.1     ,  lowercase_="gelu"     ,  lowercase_=False     ,  lowercase_=True     ,  lowercase_=0.02     ,  lowercase_=1E-5     ,  lowercase_=True     ,  lowercase_=None     ,  lowercase_=True     ,  lowercase_=10     ,  lowercase_=8     ,  )      ->   None:



             '''simple docstring'''

             _snake_case      :							List[str]     				=						parent
             _snake_case      :							str     				=						batch_size
             _snake_case      :							Any     				=						image_size
             _snake_case      :							Any     				=						patch_size
             _snake_case      :							int     				=						num_channels
             _snake_case      :							Union[str, Any]     				=						embed_dim
             _snake_case      :							List[Any]     				=						depths
             _snake_case      :							List[Any]     				=						num_heads
             _snake_case      :							Union[str, Any]     				=						window_size
             _snake_case      :							List[str]     				=						mlp_ratio
             _snake_case      :							int     				=						qkv_bias
             _snake_case      :							List[str]     				=						hidden_dropout_prob
             _snake_case      :							Any     				=						attention_probs_dropout_prob
             _snake_case      :							List[Any]     				=						drop_path_rate
             _snake_case      :							Dict     				=						hidden_act
             _snake_case      :							List[str]     				=						use_absolute_embeddings
             _snake_case      :							List[str]     				=						patch_norm
             _snake_case      :							Dict     				=						layer_norm_eps
             _snake_case      :							List[Any]     				=						initializer_range
             _snake_case      :							Optional[int]     				=						is_training
             _snake_case      :							Tuple     				=						scope
             _snake_case      :							Tuple     				=						use_labels
             _snake_case      :							List[str]     				=						type_sequence_label_size
             _snake_case      :							Optional[int]     				=						encoder_stride



      def    __a (					self					)      ->   List[Any]:



             '''simple docstring'''

             _snake_case      :							Union[str, Any]     				=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

             _snake_case      :							Union[str, Any]     				=						None
             if self.use_labels:
                    _snake_case      :							Optional[int]     				=						ids_tensor([self.batch_size]     ,  self.type_sequence_label_size					)

             _snake_case      :							List[str]     				=						self.get_config()

             return config, pixel_values, labels



      def    __a (					self					)      ->   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    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   str:



             '''simple docstring'''

             _snake_case      :							Optional[int]     				=						TFSwinModel(config=lowercase_					)
             _snake_case      :							Dict     				=						model(lowercase_					)

             _snake_case      :							str     				=						((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths					) - 1))
             _snake_case      :							Any     				=						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    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   Union[str, Any]:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						TFSwinForMaskedImageModeling(config=lowercase_					)
             _snake_case      :							Optional[Any]     				=						model(lowercase_					)
             self.parent.assertEqual(
                 result.logits.shape     ,  (self.batch_size, self.num_channels, self.image_size, self.image_size)					)

             # test greyscale images
             _snake_case      :							List[Any]     				=						1
             _snake_case      :							Optional[Any]     				=						TFSwinForMaskedImageModeling(lowercase_					)

             _snake_case      :							Optional[int]     				=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
             _snake_case      :							Optional[Any]     				=						model(lowercase_					)
             self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, 1, self.image_size, self.image_size)					)



      def    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   Union[str, Any]:



             '''simple docstring'''

             _snake_case      :							Optional[int]     				=						self.type_sequence_label_size
             _snake_case      :							Union[str, Any]     				=						TFSwinForImageClassification(lowercase_					)
             _snake_case      :							Optional[Any]     				=						model(lowercase_     ,  labels=lowercase_					)
             self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.type_sequence_label_size)					)

             # test greyscale images
             _snake_case      :							Tuple     				=						1
             _snake_case      :							Dict     				=						TFSwinForImageClassification(lowercase_					)
             _snake_case      :							str     				=						floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
             _snake_case      :							List[Any]     				=						model(lowercase_					)
             self.parent.assertEqual(result.logits.shape     ,  (self.batch_size, self.type_sequence_label_size)					)



      def    __a (					self					)      ->   Any:



             '''simple docstring'''

             _snake_case      :							Any     				=						self.prepare_config_and_inputs()
             _snake_case				,    _snake_case				,    _snake_case      :							Any     				=						config_and_inputs
             _snake_case      :							Union[str, Any]     				=						{'''pixel_values''': pixel_values}
             return config, inputs_dict


@require_tf
class 				A    (__UpperCAmelCase       ,__UpperCAmelCase       ,unittest.TestCase				):
      _SCREAMING_SNAKE_CASE					=							(
          (
              TFSwinModel,
              TFSwinForImageClassification,
              TFSwinForMaskedImageModeling,
          )
          if is_tf_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE					=							(
          {"""feature-extraction""": TFSwinModel, """image-classification""": TFSwinForImageClassification}
          if is_tf_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False



      def    __a (					self					)      ->   Any:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						TFSwinModelTester(self					)
             _snake_case      :							List[Any]     				=						ConfigTester(self     ,  config_class=lowercase_     ,  embed_dim=37					)



      def    __a (					self					)      ->   Dict:



             '''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    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             return



      def    __a (					self					)      ->   str:



             '''simple docstring'''

             _snake_case      :							int     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_					)



      def    __a (					self					)      ->   List[Any]:



             '''simple docstring'''

             _snake_case      :							Union[str, Any]     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_masked_image_modeling(*lowercase_					)



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



             '''simple docstring'''

             _snake_case      :							List[str]     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase_					)



      @unittest.skip(reason='''Swin does not use inputs_embeds'''					)
      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             pass



      def    __a (					self					)      ->   int:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Any     				=						self.model_tester.prepare_config_and_inputs_for_common()

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



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



             '''simple docstring'''

             _snake_case				,    _snake_case      :							List[str]     				=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _snake_case      :							Tuple     				=						model_class(lowercase_					)
                    _snake_case      :							Optional[int]     				=						inspect.signature(model.call					)
                    # signature.parameters is an OrderedDict => so arg_names order is deterministic
                    _snake_case      :							str     				=						[*signature.parameters.keys()]

                    _snake_case      :							Optional[int]     				=						['''pixel_values''']
                    self.assertListEqual(arg_names[:1]     ,  lowercase_					)



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



             '''simple docstring'''

             _snake_case				,    _snake_case      :							int     				=						self.model_tester.prepare_config_and_inputs_for_common()
             _snake_case      :							Optional[Any]     				=						True

             for model_class in self.all_model_classes:
                    _snake_case      :							List[Any]     				=						True
                    _snake_case      :							Any     				=						False
                    _snake_case      :							Tuple     				=						True
                    _snake_case      :							str     				=						model_class(lowercase_					)
                    _snake_case      :							List[str]     				=						model(**self._prepare_for_class(lowercase_     ,  lowercase_					)					)
                    _snake_case      :							Union[str, Any]     				=						outputs.attentions
                    _snake_case      :							Optional[int]     				=						len(self.model_tester.depths					)
                    self.assertEqual(len(lowercase_					)     ,  lowercase_					)

                    # check that output_attentions also work using config
                    del inputs_dict["output_attentions"]
                    _snake_case      :							List[str]     				=						True
                    _snake_case      :							Tuple     				=						config.window_size**2
                    _snake_case      :							Optional[Any]     				=						model_class(lowercase_					)
                    _snake_case      :							List[Any]     				=						model(**self._prepare_for_class(lowercase_     ,  lowercase_					)					)
                    _snake_case      :							Any     				=						outputs.attentions
                    self.assertEqual(len(lowercase_					)     ,  lowercase_					)

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

                    # Check attention is always last and order is fine
                    _snake_case      :							Optional[Any]     				=						True
                    _snake_case      :							str     				=						True
                    _snake_case      :							Optional[int]     				=						model_class(lowercase_					)
                    _snake_case      :							Optional[Any]     				=						model(**self._prepare_for_class(lowercase_     ,  lowercase_					)					)

                    if hasattr(self.model_tester     ,  '''num_hidden_states_types'''					):
                           _snake_case      :							Optional[int]     				=						self.model_tester.num_hidden_states_types
                    else:
                           # also another +1 for reshaped_hidden_states
                           _snake_case      :							Any     				=						2
                    self.assertEqual(out_len + added_hidden_states     ,  len(lowercase_					)					)

                    _snake_case      :							Optional[Any]     				=						outputs.attentions

                    self.assertEqual(len(lowercase_					)     ,  lowercase_					)

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



      def    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   str:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						model_class(lowercase_					)
             _snake_case      :							Tuple     				=						model(**self._prepare_for_class(lowercase_     ,  lowercase_					)					)
             _snake_case      :							Tuple     				=						outputs.hidden_states

             _snake_case      :							Optional[Any]     				=						getattr(
                 self.model_tester     ,  '''expected_num_hidden_layers'''     ,  len(self.model_tester.depths					) + 1					)
             self.assertEqual(len(lowercase_					)     ,  lowercase_					)

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

             _snake_case      :							Dict     				=						(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]     ,  )

             _snake_case      :							Optional[int]     				=						outputs.reshaped_hidden_states
             self.assertEqual(len(lowercase_					)     ,  lowercase_					)

             _snake_case				,    _snake_case				,    _snake_case				,    _snake_case      :							Optional[int]     				=						reshaped_hidden_states[0].shape

             _snake_case      :							Optional[Any]     				=						tf.reshape(reshaped_hidden_states[0]     ,  (batch_size, num_channels, height * width)					)
             _snake_case      :							List[str]     				=						tf.transpose(lowercase_     ,  (0, 2, 1)					)

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



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							List[str]     				=						self.model_tester.prepare_config_and_inputs_for_common()

             _snake_case      :							Union[str, Any]     				=						to_atuple(self.model_tester.image_size					)

             for model_class in self.all_model_classes:
                    _snake_case      :							Optional[Any]     				=						True
                    self.check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)

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

                    self.check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)



      def    __a (					self					)      ->   Any:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Union[str, Any]     				=						self.model_tester.prepare_config_and_inputs_for_common()
             _snake_case      :							Union[str, Any]     				=						3

             _snake_case      :							Optional[int]     				=						to_atuple(self.model_tester.image_size					)
             _snake_case      :							int     				=						to_atuple(config.patch_size					)

             _snake_case      :							Optional[int]     				=						image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
             _snake_case      :							int     				=						image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

             for model_class in self.all_model_classes:
                    _snake_case      :							int     				=						True
                    self.check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_     ,  (padded_height, padded_width)					)

                    # check that output_hidden_states also work using config
                    del inputs_dict["output_hidden_states"]
                    _snake_case      :							Tuple     				=						True
                    self.check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_     ,  (padded_height, padded_width)					)



      @slow
      def    __a (					self					)      ->   List[str]:



             '''simple docstring'''

             for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    _snake_case      :							List[str]     				=						TFSwinModel.from_pretrained(lowercase_					)
                    self.assertIsNotNone(lowercase_					)


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



      @cached_property
      def    __a (					self					)      ->   List[str]:



             '''simple docstring'''

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



      @slow
      def    __a (					self					)      ->   str:



             '''simple docstring'''

             _snake_case      :							Optional[Any]     				=						TFSwinForImageClassification.from_pretrained('''microsoft/swin-tiny-patch4-window7-224'''					)
             _snake_case      :							Optional[int]     				=						self.default_image_processor

             _snake_case      :							Any     				=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
             _snake_case      :							Tuple     				=						image_processor(images=lowercase_     ,  return_tensors='''tf'''					)

             # forward pass
             _snake_case      :							Dict     				=						model(lowercase_					)

             # verify the logits
             _snake_case      :							List[str]     				=						tf.TensorShape((1, 1000)					)
             self.assertEqual(outputs.logits.shape     ,  lowercase_					)
             _snake_case      :							Optional[int]     				=						tf.constant([-0.0948, -0.6454, -0.0921]					)
             self.assertTrue(np.allclose(outputs.logits[0, :3]     ,  lowercase_     ,  atol=1E-4					)					)













import cva
import numpy as np




def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_      ,		lowercase_  )			->						int:

       try:
              return int(image[x_coordinate][y_coordinate] >= center  )
       except (IndexError, TypeError):
              return 0




def 						A_			(  lowercase_      ,		lowercase_      ,		lowercase_  )			->						int:
       _snake_case      :							List[str]     				=						image[x_coordinate][y_coordinate]
       _snake_case      :							List[str]     				=						[1, 2, 4, 8, 16, 32, 64, 128]

       # skip get_neighbors_pixel if center is null
       if center is None:
              return 0

       # Starting from the top right, assigning value to pixels clockwise
       _snake_case      :							Any     				=						[
           get_neighbors_pixel(lowercase_      ,		x_coordinate - 1      ,		y_coordinate + 1      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		lowercase_      ,		y_coordinate + 1      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		x_coordinate - 1      ,		lowercase_      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		x_coordinate + 1      ,		y_coordinate + 1      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		x_coordinate + 1      ,		lowercase_      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		x_coordinate + 1      ,		y_coordinate - 1      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		lowercase_      ,		y_coordinate - 1      ,		lowercase_  ),
           get_neighbors_pixel(lowercase_      ,		x_coordinate - 1      ,		y_coordinate - 1      ,		lowercase_  ),
       ]

       # Converting the binary value to decimal.
       return sum(
           binary_value * power for binary_value, power in zip(lowercase_      ,		lowercase_  )  )


if __name__ == "__main__":
   # Reading the image and converting it to grayscale.
   lowerCAmelCase_   =   cva.imread(
       "digital_image_processing/image_data/lena.jpg", cva.IMREAD_GRAYSCALE
   )

   # Create a numpy array as the same height and width of read image
   lowerCAmelCase_   =   np.zeros((image.shape[0], image.shape[1]))

   # Iterating through the image and calculating the
   # local binary pattern value for each pixel.
   for i in range(0, image.shape[0]):
      for j in range(0, image.shape[1]):
         lowerCAmelCase_   =   local_binary_value(image, i, j)

   cva.imshow("local binary pattern", lbp_image)
   cva.waitKey(0)
   cva.destroyAllWindows()






