

from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import ResNetConfig
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 TFResNetForImageClassification, TFResNetModel
    from transformers.models.resnet.modeling_tf_resnet import TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import AutoImageProcessor






class 						__magic_name__    :


 def __init__(						self		: int			,						lowerCAmelCase__		: Any			,						lowerCAmelCase__		: Union[str, Any]=3			,						lowerCAmelCase__		: Optional[int]=3_2			,						lowerCAmelCase__		: Tuple=3			,						lowerCAmelCase__		: str=1_0			,						lowerCAmelCase__		: Optional[Any]=[1_0, 2_0, 3_0, 4_0]			,						lowerCAmelCase__		: List[str]=[1, 1, 2, 1]			,						lowerCAmelCase__		: List[Any]=True			,						lowerCAmelCase__		: int=True			,						lowerCAmelCase__		: Optional[int]="relu"			,						lowerCAmelCase__		: str=3			,						lowerCAmelCase__		: Optional[int]=None			,						)    ->      Optional[Any]:
   UpperCAmelCase					      =  parent
   UpperCAmelCase					      =  batch_size
   UpperCAmelCase					      =  image_size
   UpperCAmelCase					      =  num_channels
   UpperCAmelCase					      =  embeddings_size
   UpperCAmelCase					      =  hidden_sizes
   UpperCAmelCase					      =  depths
   UpperCAmelCase					      =  is_training
   UpperCAmelCase					      =  use_labels
   UpperCAmelCase					      =  hidden_act
   UpperCAmelCase					      =  num_labels
   UpperCAmelCase					      =  scope
   UpperCAmelCase					      =  len(lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Tuple    )    ->      List[str]:
   UpperCAmelCase					      =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

   UpperCAmelCase					      =  None
   if self.use_labels:
     UpperCAmelCase					      =  ids_tensor([self.batch_size]			,						self.num_labels    )

   UpperCAmelCase					      =  self.get_config()

   return config, pixel_values, labels


 def _UpperCamelCase	(						self		: Any    )    ->      Dict:
   return ResNetConfig(
       num_channels=self.num_channels			,						embeddings_size=self.embeddings_size			,						hidden_sizes=self.hidden_sizes			,						depths=self.depths			,						hidden_act=self.hidden_act			,						num_labels=self.num_labels			,						image_size=self.image_size			,						)


 def _UpperCamelCase	(						self		: Optional[Any]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: Union[str, Any]			,						lowerCAmelCase__		: List[str]    )    ->      Optional[int]:
   UpperCAmelCase					      =  TFResNetModel(config=lowerCAmelCase__    )
   UpperCAmelCase					      =  model(lowerCAmelCase__    )
   # 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		: Union[str, Any]			,						lowerCAmelCase__		: Tuple			,						lowerCAmelCase__		: str			,						lowerCAmelCase__		: int    )    ->      Optional[int]:
   UpperCAmelCase					      =  self.num_labels
   UpperCAmelCase					      =  TFResNetForImageClassification(lowerCAmelCase__    )
   UpperCAmelCase					      =  model(lowerCAmelCase__			,						labels=lowerCAmelCase__    )
   self.parent.assertEqual(result.logits.shape			,						(self.batch_size, self.num_labels)    )


 def _UpperCamelCase	(						self		: str    )    ->      Any:
   UpperCAmelCase					      =  self.prepare_config_and_inputs()
   UpperCAmelCase      ,	UpperCAmelCase      ,	UpperCAmelCase					      =  config_and_inputs
   UpperCAmelCase					      =  {"pixel_values": pixel_values}
   return config, inputs_dict






@require_tf
class 						__magic_name__    (       _snake_case	,						_snake_case	,						unittest.TestCase    ):
 UpperCAmelCase							    =						(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 UpperCAmelCase							    =						(
     {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False
 UpperCAmelCase							    =						False


 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      Union[str, Any]:
   UpperCAmelCase					      =  TFResNetModelTester(self    )
   UpperCAmelCase					      =  ConfigTester(self			,						config_class=lowerCAmelCase__			,						has_text_modality=lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Dict    )    ->      Union[str, 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 _UpperCamelCase	(						self		: Optional[Any]    )    ->      Optional[int]:
   return


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


 @unittest.skip(reason="ResNet does not support input and output embeddings"    )
 def _UpperCamelCase	(						self		: str    )    ->      Dict:
   pass


 def _UpperCamelCase	(						self		: Dict    )    ->      int:
   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()

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

     UpperCAmelCase					      =  ["pixel_values"]
     self.assertListEqual(arg_names[:1]			,						lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: int    )    ->      str:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_model(*lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      List[Any]:
   def check_hidden_states_output(lowerCAmelCase__		: Dict			,						lowerCAmelCase__		: Optional[Any]			,						lowerCAmelCase__		: List[Any]    ):
     UpperCAmelCase					      =  model_class(lowerCAmelCase__    )
     UpperCAmelCase					      =  model(**self._prepare_for_class(lowerCAmelCase__			,						lowerCAmelCase__    )    )

     UpperCAmelCase					      =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

     UpperCAmelCase					      =  self.model_tester.num_stages
     self.assertEqual(len(lowerCAmelCase__    )			,						expected_num_stages + 1    )

     # ResNet'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]			,						)

   UpperCAmelCase      ,	UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs_for_common()
   UpperCAmelCase					      =  ["basic", "bottleneck"]
   for model_class in self.all_model_classes:
     for layer_type in layers_type:
       UpperCAmelCase					      =  layer_type
       UpperCAmelCase					      =  True
       check_hidden_states_output(lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__    )

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

       check_hidden_states_output(lowerCAmelCase__			,						lowerCAmelCase__			,						lowerCAmelCase__    )


 def _UpperCamelCase	(						self		: Tuple    )    ->      Optional[Any]:
   UpperCAmelCase					      =  self.model_tester.prepare_config_and_inputs()
   self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__    )


 @slow
 def _UpperCamelCase	(						self		: Union[str, Any]    )    ->      int:
   for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     UpperCAmelCase					      =  TFResNetModel.from_pretrained(lowerCAmelCase__    )
     self.assertIsNotNone(lowerCAmelCase__    )

def      _lowerCAmelCase(	):
  UpperCAmelCase					      =  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"			)
  return image






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


 @cached_property
 def _UpperCamelCase	(						self		: Optional[Any]    )    ->      Any:
   return (
       AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )
       if is_vision_available()
       else None
   )


 @slow
 def _UpperCamelCase	(						self		: List[str]    )    ->      Union[str, Any]:
   UpperCAmelCase					      =  TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

   UpperCAmelCase					      =  self.default_image_processor
   UpperCAmelCase					      =  prepare_img()
   UpperCAmelCase					      =  image_processor(images=lowerCAmelCase__			,						return_tensors="tf"    )

   # forward pass
   UpperCAmelCase					      =  model(**lowerCAmelCase__    )

   # verify the logits
   UpperCAmelCase					      =  tf.TensorShape((1, 1_0_0_0)    )
   self.assertEqual(outputs.logits.shape			,						lowerCAmelCase__    )

   UpperCAmelCase					      =  tf.constant([-11.1_069, -9.7_877, -8.3_777]    )

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






import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from requests.exceptions import HTTPError

from transformers import AutoFeatureExtractor, WavaVecaFeatureExtractor
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test


sys.path.append(str(Path(__file__).parent.parent / "utils"))

from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


lowerCAmelCase__       = get_tests_dir("fixtures")






class 						__magic_name__    (       unittest.TestCase    ):


 def _UpperCamelCase	(						self		: Tuple    )    ->      Union[str, Any]:
   # A mock response for an HTTP head request to emulate server down
   UpperCAmelCase					      =  mock.Mock()
   UpperCAmelCase					      =  5_0_0
   UpperCAmelCase					      =  {}
   UpperCAmelCase					      =  HTTPError
   UpperCAmelCase					      =  {}

   # Download this model to make sure it's in the cache.
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"    )
   # Under the mock environment we get a 500 error when trying to reach the model.
   with mock.patch("requests.Session.request"			,						return_value=lowerCAmelCase__    ) as mock_head:
     UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2"    )
     # This check we did call the fake head request
     mock_head.assert_called()


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Dict:
   # This test is for deprecated behavior and can be removed in v5
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(
       "https://huggingface.co/hf-internal-testing/tiny-random-wav2vec2/resolve/main/preprocessor_config.json"    )






@is_staging_test
class 						__magic_name__    (       unittest.TestCase    ):


 @classmethod
 def _UpperCamelCase	(						cls		: List[str]    )    ->      List[Any]:
   UpperCAmelCase					      =  TOKEN
   HfFolder.save_token(lowerCAmelCase__    )


 @classmethod
 def _UpperCamelCase	(						cls		: Optional[int]    )    ->      Union[str, Any]:
   try:
     delete_repo(token=cls._token			,						repo_id="test-feature-extractor"    )
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token			,						repo_id="valid_org/test-feature-extractor-org"    )
   except HTTPError:
     pass

   try:
     delete_repo(token=cls._token			,						repo_id="test-dynamic-feature-extractor"    )
   except HTTPError:
     pass


 def _UpperCamelCase	(						self		: Any    )    ->      Any:
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase__    )
   feature_extractor.push_to_hub("test-feature-extractor"			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )

   # Reset repo
   delete_repo(token=self._token			,						repo_id="test-feature-extractor"    )

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(
         lowerCAmelCase__			,						repo_id="test-feature-extractor"			,						push_to_hub=lowerCAmelCase__			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(f"{USER}/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: List[Any]    )    ->      Tuple:
   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained(lowerCAmelCase__    )
   feature_extractor.push_to_hub("valid_org/test-feature-extractor"			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )

   # Reset repo
   delete_repo(token=self._token			,						repo_id="valid_org/test-feature-extractor"    )

   # Push to hub via save_pretrained
   with tempfile.TemporaryDirectory() as tmp_dir:
     feature_extractor.save_pretrained(
         lowerCAmelCase__			,						repo_id="valid_org/test-feature-extractor-org"			,						push_to_hub=lowerCAmelCase__			,						use_auth_token=self._token    )

   UpperCAmelCase					      =  WavaVecaFeatureExtractor.from_pretrained("valid_org/test-feature-extractor-org"    )
   for k, v in feature_extractor.__dict__.items():
     self.assertEqual(lowerCAmelCase__			,						getattr(lowerCAmelCase__			,						lowerCAmelCase__    )    )


 def _UpperCamelCase	(						self		: Dict    )    ->      List[str]:
   CustomFeatureExtractor.register_for_auto_class()
   UpperCAmelCase					      =  CustomFeatureExtractor.from_pretrained(lowerCAmelCase__    )

   feature_extractor.push_to_hub("test-dynamic-feature-extractor"			,						use_auth_token=self._token    )

   # This has added the proper auto_map field to the config
   self.assertDictEqual(
       feature_extractor.auto_map			,						{"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}			,						)

   UpperCAmelCase					      =  AutoFeatureExtractor.from_pretrained(
       f"{USER}/test-dynamic-feature-extractor"			,						trust_remote_code=lowerCAmelCase__    )
   # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module
   self.assertEqual(new_feature_extractor.__class__.__name__			,						"CustomFeatureExtractor"    )



