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       __snake_case :
 def __init__(	self		, snake_case__		, snake_case__=13		, snake_case__=32		, snake_case__=2		, snake_case__=3		, snake_case__=16		, snake_case__=[1, 2, 1]		, snake_case__=[2, 2, 4]		, snake_case__=2		, snake_case__=2.0		, snake_case__=True		, snake_case__=0.0		, snake_case__=0.0		, snake_case__=0.1		, snake_case__="gelu"		, snake_case__=False		, snake_case__=True		, snake_case__=0.02		, snake_case__=1e-5		, snake_case__=True		, snake_case__=None		, snake_case__=True		, snake_case__=10		, snake_case__=8		, )						->				int:
       '''simple docstring'''





       UpperCAmelCase     :			List[Any]     	=parent
       UpperCAmelCase     :			Tuple     	=batch_size
       UpperCAmelCase     :			str     	=image_size
       UpperCAmelCase     :			int     	=patch_size
       UpperCAmelCase     :			Dict     	=num_channels
       UpperCAmelCase     :			Optional[int]     	=embed_dim
       UpperCAmelCase     :			Dict     	=depths
       UpperCAmelCase     :			Tuple     	=num_heads
       UpperCAmelCase     :			List[str]     	=window_size
       UpperCAmelCase     :			Optional[int]     	=mlp_ratio
       UpperCAmelCase     :			Dict     	=qkv_bias
       UpperCAmelCase     :			Dict     	=hidden_dropout_prob
       UpperCAmelCase     :			Optional[int]     	=attention_probs_dropout_prob
       UpperCAmelCase     :			Optional[Any]     	=drop_path_rate
       UpperCAmelCase     :			Optional[int]     	=hidden_act
       UpperCAmelCase     :			Optional[Any]     	=use_absolute_embeddings
       UpperCAmelCase     :			Dict     	=patch_norm
       UpperCAmelCase     :			str     	=layer_norm_eps
       UpperCAmelCase     :			Dict     	=initializer_range
       UpperCAmelCase     :			Optional[int]     	=is_training
       UpperCAmelCase     :			Any     	=scope
       UpperCAmelCase     :			int     	=use_labels
       UpperCAmelCase     :			Union[str, Any]     	=type_sequence_label_size
       UpperCAmelCase     :			int     	=encoder_stride
 def 						UpperCAmelCase__							(	self    )						->				List[Any]:
       '''simple docstring'''





       UpperCAmelCase     :			Any     	=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

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

       return config, pixel_values, labels
 def 						UpperCAmelCase__							(	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 						UpperCAmelCase__							(	self		, snake_case__		, snake_case__		, snake_case__    )						->				List[Any]:
       '''simple docstring'''





       UpperCAmelCase     :			List[Any]     	=TFSwinModel(config=lowerCamelCase__    )
       UpperCAmelCase     :			Optional[int]     	=model(lowerCamelCase__    )

       UpperCAmelCase     :			Tuple     	=((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
       UpperCAmelCase     :			Dict     	=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 						UpperCAmelCase__							(	self		, snake_case__		, snake_case__		, snake_case__    )						->				Dict:
       '''simple docstring'''





       UpperCAmelCase     :			Dict     	=TFSwinForMaskedImageModeling(config=lowerCamelCase__    )
       UpperCAmelCase     :			List[str]     	=model(lowerCamelCase__    )
       self.parent.assertEqual(
           result.logits.shape		, (self.batch_size, self.num_channels, self.image_size, self.image_size)    )

       # test greyscale images
       UpperCAmelCase     :			Dict     	=1
       UpperCAmelCase     :			Union[str, Any]     	=TFSwinForMaskedImageModeling(lowerCamelCase__    )

       UpperCAmelCase     :			Optional[Any]     	=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
       UpperCAmelCase     :			List[Any]     	=model(lowerCamelCase__    )
       self.parent.assertEqual(result.logits.shape		, (self.batch_size, 1, self.image_size, self.image_size)    )
 def 						UpperCAmelCase__							(	self		, snake_case__		, snake_case__		, snake_case__    )						->				Any:
       '''simple docstring'''





       UpperCAmelCase     :			str     	=self.type_sequence_label_size
       UpperCAmelCase     :			Union[str, Any]     	=TFSwinForImageClassification(lowerCamelCase__    )
       UpperCAmelCase     :			str     	=model(lowerCamelCase__		, labels=lowerCamelCase__    )
       self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.type_sequence_label_size)    )

       # test greyscale images
       UpperCAmelCase     :			Optional[Any]     	=1
       UpperCAmelCase     :			int     	=TFSwinForImageClassification(lowerCamelCase__    )
       UpperCAmelCase     :			Union[str, Any]     	=floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
       UpperCAmelCase     :			List[str]     	=model(lowerCamelCase__    )
       self.parent.assertEqual(result.logits.shape		, (self.batch_size, self.type_sequence_label_size)    )






 def 						UpperCAmelCase__							(	self    )						->				Optional[int]:
       '''simple docstring'''





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







@require_tf
class       __snake_case (  lowerCamelCase__       , lowerCamelCase__       , unittest.TestCase ):
 __lowerCamelCase     : Tuple 	=   (
     (
         TFSwinModel,
         TFSwinForImageClassification,
         TFSwinForMaskedImageModeling,
     )
     if is_tf_available()
     else ()
 )
 __lowerCamelCase     : Optional[Any] 	=   (
     {"""feature-extraction""": TFSwinModel, """image-classification""": TFSwinForImageClassification}
     if is_tf_available()
     else {}
 )

 __lowerCamelCase     : Any 	=   False
 __lowerCamelCase     : Tuple 	=   False
 __lowerCamelCase     : Tuple 	=   False
 __lowerCamelCase     : Tuple 	=   False
 def 						UpperCAmelCase__							(	self    )						->				Optional[int]:
       '''simple docstring'''





       UpperCAmelCase     :			Dict     	=TFSwinModelTester(self    )
       UpperCAmelCase     :			int     	=ConfigTester(self		, config_class=lowerCamelCase__		, embed_dim=37    )
 def 						UpperCAmelCase__							(	self    )						->				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 						UpperCAmelCase__							(	self    )						->				Union[str, Any]:
       '''simple docstring'''





       return
 def 						UpperCAmelCase__							(	self    )						->				Optional[int]:
       '''simple docstring'''





       UpperCAmelCase     :			Union[str, Any]     	=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase__    )
 def 						UpperCAmelCase__							(	self    )						->				Optional[int]:
       '''simple docstring'''





       UpperCAmelCase     :			List[str]     	=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_image_modeling(*lowerCamelCase__    )
 def 						UpperCAmelCase__							(	self    )						->				List[str]:
       '''simple docstring'''





       UpperCAmelCase     :			List[Any]     	=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__    )
 @unittest.skip(reason='''Swin does not use inputs_embeds'''    )
 def 						UpperCAmelCase__							(	self    )						->				str:
       '''simple docstring'''





       pass
 def 						UpperCAmelCase__							(	self    )						->				str:
       '''simple docstring'''





       UpperCAmelCase     :			int     	=self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             UpperCAmelCase     :			Union[str, Any]     	=model_class(lowerCamelCase__    )
             self.assertIsInstance(model.get_input_embeddings()		, tf.keras.layers.Layer    )
             UpperCAmelCase     :			List[str]     	=model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(lowerCamelCase__		, tf.keras.layers.Dense    )    )
 def 						UpperCAmelCase__							(	self    )						->				Tuple:
       '''simple docstring'''





       UpperCAmelCase     :			Optional[Any]     	=self.model_tester.prepare_config_and_inputs_for_common()

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

             UpperCAmelCase     :			Any     	=['pixel_values']
             self.assertListEqual(arg_names[:1]		, lowerCamelCase__    )
 def 						UpperCAmelCase__							(	self    )						->				List[Any]:
       '''simple docstring'''





       UpperCAmelCase     :			Any     	=self.model_tester.prepare_config_and_inputs_for_common()
       UpperCAmelCase     :			Any     	=True

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

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

             self.assertListEqual(
                 list(attentions[0].shape[-3:]    )		, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]		, )
             UpperCAmelCase     :			Union[str, Any]     	=len(lowerCamelCase__    )

             # Check attention is always last and order is fine
             UpperCAmelCase     :			Dict     	=True
             UpperCAmelCase     :			Tuple     	=True
             UpperCAmelCase     :			Union[str, Any]     	=model_class(lowerCamelCase__    )
             UpperCAmelCase     :			int     	=model(**self._prepare_for_class(lowerCamelCase__		, lowerCamelCase__    )    )

             if hasattr(self.model_tester		, '''num_hidden_states_types'''    ):
                   UpperCAmelCase     :			Union[str, Any]     	=self.model_tester.num_hidden_states_types
             else:
                   # also another +1 for reshaped_hidden_states
                   UpperCAmelCase     :			Union[str, Any]     	=2
             self.assertEqual(out_len + added_hidden_states		, len(lowerCamelCase__    )    )

             UpperCAmelCase     :			int     	=outputs.attentions

             self.assertEqual(len(lowerCamelCase__    )		, lowerCamelCase__    )

             self.assertListEqual(
                 list(self_attentions[0].shape[-3:]    )		, [self.model_tester.num_heads[0], window_size_squared, window_size_squared]		, )
 def 						UpperCAmelCase__							(	self		, snake_case__		, snake_case__		, snake_case__		, snake_case__    )						->				List[str]:
       '''simple docstring'''





       UpperCAmelCase     :			List[Any]     	=model_class(lowerCamelCase__    )
       UpperCAmelCase     :			Optional[Any]     	=model(**self._prepare_for_class(lowerCamelCase__		, lowerCamelCase__    )    )
       UpperCAmelCase     :			Optional[int]     	=outputs.hidden_states

       UpperCAmelCase     :			Dict     	=getattr(
           self.model_tester		, '''expected_num_hidden_layers'''		, len(self.model_tester.depths    ) + 1    )
       self.assertEqual(len(lowerCamelCase__    )		, lowerCamelCase__    )

       # Swin has a different seq_length
       UpperCAmelCase     :			Union[str, Any]     	=to_atuple(config.patch_size    )

       UpperCAmelCase     :			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]		, )

       UpperCAmelCase     :			List[Any]     	=outputs.reshaped_hidden_states
       self.assertEqual(len(lowerCamelCase__    )		, lowerCamelCase__    )

       UpperCAmelCase     :			List[str]     	=reshaped_hidden_states[0].shape

       UpperCAmelCase     :			Dict     	=tf.reshape(reshaped_hidden_states[0]		, (batch_size, num_channels, height * width)    )
       UpperCAmelCase     :			Any     	=tf.transpose(lowerCamelCase__		, (0, 2, 1)    )

       self.assertListEqual(
           list(reshaped_hidden_states.shape[-2:]    )		, [num_patches, self.model_tester.embed_dim]		, )
 def 						UpperCAmelCase__							(	self    )						->				Optional[Any]:
       '''simple docstring'''





       UpperCAmelCase     :			int     	=self.model_tester.prepare_config_and_inputs_for_common()

       UpperCAmelCase     :			Tuple     	=to_atuple(self.model_tester.image_size    )

       for model_class in self.all_model_classes:
             UpperCAmelCase     :			Dict     	=True
             self.check_hidden_states_output(lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__    )

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

             self.check_hidden_states_output(lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__    )
 def 						UpperCAmelCase__							(	self    )						->				Tuple:
       '''simple docstring'''





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

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

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

       for model_class in self.all_model_classes:
             UpperCAmelCase     :			Any     	=True
             self.check_hidden_states_output(lowerCamelCase__		, lowerCamelCase__		, lowerCamelCase__		, (padded_height, padded_width)    )

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






 @slow
 def 						UpperCAmelCase__							(	self    )						->				Any:
       '''simple docstring'''





       for model_name in TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             UpperCAmelCase     :			Optional[int]     	=TFSwinModel.from_pretrained(lowerCamelCase__    )
             self.assertIsNotNone(lowerCamelCase__    )







@require_vision
@require_tf
class       __snake_case (  unittest.TestCase ):
 @cached_property
 def 						UpperCAmelCase__							(	self    )						->				Any:
       '''simple docstring'''





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






 @slow
 def 						UpperCAmelCase__							(	self    )						->				Dict:
       '''simple docstring'''





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

       UpperCAmelCase     :			str     	=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
       UpperCAmelCase     :			List[str]     	=image_processor(images=lowerCamelCase__		, return_tensors='''tf'''    )

       # forward pass
       UpperCAmelCase     :			Tuple     	=model(lowerCamelCase__    )

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








from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier

# Load iris file
A_			:Union[str, Any]	    =		load_iris()
iris.keys()


print(f"Target names: \n {iris.target_names} ")
print(f"\n Features: \n {iris.feature_names}")

# Train set e Test set
A_    ,A_    ,A_    ,A_			:Tuple	    =		train_test_split(
    iris['''data'''], iris['''target'''], random_state=4
)

# KNN

A_			:Any	    =		KNeighborsClassifier(n_neighbors=1)
knn.fit(X_train, y_train)

# new array to test
A_			:Optional[Any]	    =		[[1, 2, 1, 4], [2, 3, 4, 5]]

A_			:Union[str, Any]	    =		knn.predict(X_new)

print(
    f"\nNew array: \n {X_new}\n\nTarget Names Prediction: \n"
    f" {iris['target_names'][prediction]}"
)

