




import inspect
import unittest

from transformers import ConvNextConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import ConvNextBackbone, ConvNextForImageClassification, ConvNextModel
  from transformers.models.convnext.modeling_convnext import CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class 		lowercase							:

     def __init__(						self	,  _a	,  _a=13	,  _a=32	,  _a=3	,  _a=4	,  _a=[10, 20, 30, 40]	,  _a=[2, 2, 3, 2]	,  _a=True	,  _a=True	,  _a=37	,  _a="gelu"	,  _a=10	,  _a=0.02	,  _a=["stage2", "stage3", "stage4"]	,  _a=[2, 3, 4]	,  _a=None	,  )		->							str:
           _A							:  Optional[int]    =		parent
           _A							:  List[Any]    =		batch_size
           _A							:  List[str]    =		image_size
           _A							:  Optional[int]    =		num_channels
           _A							:  Optional[Any]    =		num_stages
           _A							:  Optional[int]    =		hidden_sizes
           _A							:  Optional[Any]    =		depths
           _A							:  int    =		is_training
           _A							:  Any    =		use_labels
           _A							:  Optional[Any]    =		intermediate_size
           _A							:  Optional[int]    =		hidden_act
           _A							:  Union[str, Any]    =		num_labels
           _A							:  Dict    =		initializer_range
           _A							:  Dict    =		out_features
           _A							:  List[str]    =		out_indices
           _A							:  int    =		scope

     def       a__			(						self       )		->							Tuple:
           _A							:  Union[str, Any]    =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

           _A							:  Optional[Any]    =		None
           if self.use_labels:
                 _A							:  List[Any]    =		ids_tensor([self.batch_size]	,  self.num_labels       )

           _A							:  List[Any]    =		self.get_config()
           return config, pixel_values, labels

     def       a__			(						self       )		->							Dict:
           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=_a	,  initializer_range=self.initializer_range	,  out_features=self.out_features	,  out_indices=self.out_indices	,  num_labels=self.num_labels	,  )

     def       a__			(						self	,  _a	,  _a	,  _a       )		->							Any:
           _A							:  int    =		ConvNextModel(config=_a       )
           model.to(_a       )
           model.eval()
           _A							:  Union[str, Any]    =		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	,  _a	,  _a	,  _a       )		->							Optional[int]:
           _A							:  List[str]    =		ConvNextForImageClassification(_a       )
           model.to(_a       )
           model.eval()
           _A							:  Dict    =		model(_a	,  labels=_a       )
           self.parent.assertEqual(result.logits.shape	,  (self.batch_size, self.num_labels)       )

     def       a__			(						self	,  _a	,  _a	,  _a       )		->							Optional[int]:
           _A							:  str    =		ConvNextBackbone(config=_a       )
           model.to(_a       )
           model.eval()
           _A							:  List[str]    =		model(_a       )

           # verify hidden states
           self.parent.assertEqual(len(result.feature_maps       )	,  len(config.out_features       )       )
           self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,  [self.batch_size, self.hidden_sizes[1], 4, 4]       )

           # verify channels
           self.parent.assertEqual(len(model.channels       )	,  len(config.out_features       )       )
           self.parent.assertListEqual(model.channels	,  config.hidden_sizes[1:]       )

           # verify backbone works with out_features=None
           _A							:  Dict    =		None
           _A							:  Dict    =		ConvNextBackbone(config=_a       )
           model.to(_a       )
           model.eval()
           _A							:  Optional[Any]    =		model(_a       )

           # verify feature maps
           self.parent.assertEqual(len(result.feature_maps       )	,  1       )
           self.parent.assertListEqual(list(result.feature_maps[0].shape       )	,  [self.batch_size, self.hidden_sizes[-1], 1, 1]       )

           # verify channels
           self.parent.assertEqual(len(model.channels       )	,  1       )
           self.parent.assertListEqual(model.channels	,  [config.hidden_sizes[-1]]       )



     def       a__			(						self       )		->							Any:
           _A							:  List[str]    =		self.prepare_config_and_inputs()
           _A    ,     _A    ,     _A							:  Tuple    =		config_and_inputs
           _A							:  Tuple    =		{"""pixel_values""": pixel_values}
           return config, inputs_dict







@require_torch
class 		lowercase							(     UpperCamelCase__,UpperCamelCase__,unittest.TestCase	):
     _a											=		(
         (
             ConvNextModel,
             ConvNextForImageClassification,
             ConvNextBackbone,
         )
         if is_torch_available()
         else ()
     )
     _a											=		(
         {"feature-extraction": ConvNextModel, "image-classification": ConvNextForImageClassification}
         if is_torch_available()
         else {}
     )

     _a											=		True
     _a											=		False
     _a											=		False
     _a											=		False
     _a											=		False

     def       a__			(						self       )		->							Dict:
           _A							:  Tuple    =		ConvNextModelTester(self       )
           _A							:  Optional[int]    =		ConfigTester(self	,  config_class=_a	,  has_text_modality=_a	,  hidden_size=37       )

     def       a__			(						self       )		->							Optional[Any]:
           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       )		->							List[str]:
           return

     @unittest.skip(reason="""ConvNext does not use inputs_embeds"""       )
     def       a__			(						self       )		->							Any:
           pass

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

     @unittest.skip(reason="""ConvNext does not use feedforward chunking"""       )
     def       a__			(						self       )		->							List[str]:
           pass

     def       a__			(						self       )		->							Optional[int]:
           _A    ,     _A							:  str    =		self.model_tester.prepare_config_and_inputs_for_common()

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

                 _A							:  List[str]    =		["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]	,  _a       )

     def       a__			(						self       )		->							int:
           _A							:  str    =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*_a       )

     def       a__			(						self       )		->							Union[str, Any]:
           _A							:  Dict    =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_backbone(*_a       )

     def       a__			(						self       )		->							Optional[Any]:
           def check_hidden_states_output(_a	,  _a	,  _a       ):
                 _A							:  Any    =		model_class(_a       )
                 model.to(_a       )
                 model.eval()

                 with torch.no_grad():
                       _A							:  str    =		model(**self._prepare_for_class(_a	,  _a       )       )

                 _A							:  Optional[Any]    =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 _A							:  Dict    =		self.model_tester.num_stages
                 self.assertEqual(len(_a       )	,  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]	,  )

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

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

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 _A							:  Optional[Any]    =		True

                 check_hidden_states_output(_a	,  _a	,  _a       )

     def       a__			(						self       )		->							List[str]:
           _A							:  List[Any]    =		self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*_a       )



     @slow
     def       a__			(						self       )		->							List[str]:
           for model_name in CONVNEXT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _A							:  Optional[Any]    =		ConvNextModel.from_pretrained(_a       )
                 self.assertIsNotNone(_a       )







def        lowerCAmelCase_			(  ):
      _A							:  str    =		Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""  )
      return image







@require_torch
@require_vision
class 		lowercase							(     unittest.TestCase	):

     @cached_property
     def       a__			(						self       )		->							Dict:
           return AutoImageProcessor.from_pretrained("""facebook/convnext-tiny-224"""       ) if is_vision_available() else None



     @slow
     def       a__			(						self       )		->							List[str]:
           _A							:  List[Any]    =		ConvNextForImageClassification.from_pretrained("""facebook/convnext-tiny-224"""       ).to(_a       )

           _A							:  Optional[Any]    =		self.default_image_processor
           _A							:  Union[str, Any]    =		prepare_img()
           _A							:  int    =		image_processor(images=_a	,  return_tensors="""pt"""       ).to(_a       )

           # forward pass
           with torch.no_grad():
                 _A							:  Tuple    =		model(**_a       )

           # verify the logits
           _A							:  Tuple    =		torch.Size((1, 1000)       )
           self.assertEqual(outputs.logits.shape	,  _a       )

           _A							:  str    =		torch.tensor([-0.0260, -0.4739, 0.1911]       ).to(_a       )

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







@require_torch
class 		lowercase							(     unittest.TestCase,UpperCamelCase__	):
     _a											=		(ConvNextBackbone,) if is_torch_available() else ()
     _a											=		ConvNextConfig

     _a											=		False

     def       a__			(						self       )		->							Optional[int]:
           _A							:  Union[str, Any]    =		ConvNextModelTester(self       )







from __future__ import annotations







class 		lowercase							:

     def __init__(						self	,  _a = 0       )		->							str:
           _A							:  Any    =		key

     def       a__			(						self	,  _a	,  _a       )		->							list[str]:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           _A							:  Any    =		key or self.__key or 1

           # make sure key is an appropriate size
           key %= 255

           return [chr(ord(_a       ) ^ key       ) for ch in content]

     def       a__			(						self	,  _a	,  _a       )		->							list[str]:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           _A							:  List[Any]    =		key or self.__key or 1

           # make sure key is an appropriate size
           key %= 255

           return [chr(ord(_a       ) ^ key       ) for ch in content]

     def       a__			(						self	,  _a	,  _a = 0       )		->							str:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           _A							:  List[Any]    =		key or self.__key or 1

           # make sure key can be any size
           while key > 255:
                 key -= 255

           # This will be returned
           _A							:  List[str]    =		""""""

           for ch in content:
                 ans += chr(ord(_a       ) ^ key       )

           return ans

     def       a__			(						self	,  _a	,  _a = 0       )		->							str:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           _A							:  List[str]    =		key or self.__key or 1

           # make sure key can be any size
           while key > 255:
                 key -= 255

           # This will be returned
           _A							:  List[str]    =		""""""

           for ch in content:
                 ans += chr(ord(_a       ) ^ key       )

           return ans

     def       a__			(						self	,  _a	,  _a = 0       )		->							bool:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           try:
                 with open(_a       ) as fin, open("""encrypt.out"""	,  """w+"""       ) as fout:
                       # actual encrypt-process
                       for line in fin:
                             fout.write(self.encrypt_string(_a	,  _a       )       )

           except OSError:
                 return False

           return True



     def       a__			(						self	,  _a	,  _a       )		->							bool:
           assert isinstance(_a	,  _a       ) and isinstance(_a	,  _a       )

           try:
                 with open(_a       ) as fin, open("""decrypt.out"""	,  """w+"""       ) as fout:
                       # actual encrypt-process
                       for line in fin:
                             fout.write(self.decrypt_string(_a	,  _a       )       )

           except OSError:
                 return False

           return True


# Tests
# crypt = XORCipher()
# key = 67

# # test encrypt
# print(crypt.encrypt("hallo welt",key))
# # test decrypt
# print(crypt.decrypt(crypt.encrypt("hallo welt",key), key))

# # test encrypt_string
# print(crypt.encrypt_string("hallo welt",key))

# # test decrypt_string
# print(crypt.decrypt_string(crypt.encrypt_string("hallo welt",key),key))

# if (crypt.encrypt_file("test.txt",key)):
#       print("encrypt successful")
# else:
#       print("encrypt unsuccessful")

# if (crypt.decrypt_file("encrypt.out",key)):
#       print("decrypt successful")
# else:
#       print("decrypt unsuccessful")

