

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



 """simple docstring"""







 def __init__(		self :	Tuple     ,						A_ :	Optional[Any]     ,						A_ :	str=3     ,						A_ :	Union[str, Any]=3_2     ,						A_ :	Tuple=3     ,						A_ :	Optional[Any]=1_0     ,						A_ :	Tuple=[1_0, 2_0, 3_0, 4_0]     ,						A_ :	Optional[int]=[1, 1, 2, 1]     ,						A_ :	Optional[int]=True     ,						A_ :	Dict=True     ,						A_ :	List[Any]="relu"     ,						A_ :	Union[str, Any]=3     ,						A_ :	Union[str, Any]=None     ,						):






      '''simple docstring'''




      _lowerCAmelCase   :					str        =    parent
      _lowerCAmelCase   :					Dict        =    batch_size
      _lowerCAmelCase   :					List[Any]        =    image_size
      _lowerCAmelCase   :					Tuple        =    num_channels
      _lowerCAmelCase   :					Dict        =    embeddings_size
      _lowerCAmelCase   :					List[str]        =    hidden_sizes
      _lowerCAmelCase   :					Any        =    depths
      _lowerCAmelCase   :					Union[str, Any]        =    is_training
      _lowerCAmelCase   :					List[Any]        =    use_labels
      _lowerCAmelCase   :					List[Any]        =    hidden_act
      _lowerCAmelCase   :					Tuple        =    num_labels
      _lowerCAmelCase   :					List[str]        =    scope
      _lowerCAmelCase   :					Optional[Any]        =    len(_a       )

 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




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

      _lowerCAmelCase   :					str        =    None
      if self.use_labels:
           _lowerCAmelCase   :					Dict        =    ids_tensor([self.batch_size]     ,						self.num_labels       )

      _lowerCAmelCase   :					str        =    self.get_config()

      return config, pixel_values, labels

 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      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    __magic_name__       (		self :	Optional[Any]     ,						A_ :	int     ,						A_ :	Dict     ,						A_ :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    TFResNetModel(config=_a       )
      _lowerCAmelCase   :					int        =    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 // 3_2, self.image_size // 3_2)     ,						)

 def    __magic_name__       (		self :	Union[str, Any]     ,						A_ :	List[Any]     ,						A_ :	Any     ,						A_ :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    self.num_labels
      _lowerCAmelCase   :					Optional[int]        =    TFResNetForImageClassification(_a       )
      _lowerCAmelCase   :					List[str]        =    model(_a     ,						labels=_a       )
      self.parent.assertEqual(result.logits.shape     ,						(self.batch_size, self.num_labels)       )


 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    self.prepare_config_and_inputs()
      _lowerCAmelCase   :					Optional[Any]        =    config_and_inputs
      _lowerCAmelCase   :					Dict        =    {"""pixel_values""": pixel_values}
      return config, inputs_dict





@require_tf
class A__	( UpperCamelCase_  ,		UpperCamelCase_  ,		unittest.TestCase ):



 """simple docstring"""







 _lowercase     :					List[str]      =						(TFResNetModel, TFResNetForImageClassification) if is_tf_available() else ()
 _lowercase     :					Optional[Any]      =						(
     {"""feature-extraction""": TFResNetModel, """image-classification""": TFResNetForImageClassification}
     if is_tf_available()
     else {}
 )

 _lowercase     :					Tuple      =						False
 _lowercase     :					Union[str, Any]      =						False
 _lowercase     :					Tuple      =						False
 _lowercase     :					Optional[Any]      =						False
 _lowercase     :					Dict      =						False

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Dict        =    TFResNetModelTester(self       )
      _lowerCAmelCase   :					Dict        =    ConfigTester(self     ,						config_class=_a     ,						has_text_modality=_a       )

 def    __magic_name__       (		self :	Tuple       ):






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






      '''simple docstring'''




      return

 @unittest.skip(reason="ResNet does not use inputs_embeds"       )
 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      pass

 @unittest.skip(reason="ResNet does not support input and output embeddings"       )
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      pass

 def    __magic_name__       (		self :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    self.model_tester.prepare_config_and_inputs_for_common()

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

           _lowerCAmelCase   :					Any        =    ["""pixel_values"""]
           self.assertListEqual(arg_names[:1]     ,						_a       )

 def    __magic_name__       (		self :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_a       )

 def    __magic_name__       (		self :	Optional[int]       ):






      '''simple docstring'''




      def check_hidden_states_output(A_ :	Optional[int]     ,						A_ :	Optional[int]     ,						A_ :	int       ):
           _lowerCAmelCase   :					Dict        =    model_class(_a       )
           _lowerCAmelCase   :					Dict        =    model(**self._prepare_for_class(_a     ,						_a       )       )

           _lowerCAmelCase   :					Optional[int]        =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

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

      _lowerCAmelCase   :					Dict        =    self.model_tester.prepare_config_and_inputs_for_common()
      _lowerCAmelCase   :					Optional[int]        =    ["""basic""", """bottleneck"""]
      for model_class in self.all_model_classes:
           for layer_type in layers_type:
                _lowerCAmelCase   :					Dict        =    layer_type
                _lowerCAmelCase   :					Union[str, Any]        =    True
                check_hidden_states_output(_a     ,						_a     ,						_a       )

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

                check_hidden_states_output(_a     ,						_a     ,						_a       )

 def    __magic_name__       (		self :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					str        =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*_a       )


 @slow
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      for model_name in TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowerCAmelCase   :					Optional[Any]        =    TFResNetModel.from_pretrained(_a       )
           self.assertIsNotNone(_a       )







def 	_snake_case		(    )       ->      List[Any]:

     """simple docstring"""







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





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



 """simple docstring"""







 @cached_property
 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




      return (
          AutoImageProcessor.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
          if is_vision_available()
          else None
      )


 @slow
 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    TFResNetForImageClassification.from_pretrained(TF_RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )

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

      # forward pass
      _lowerCAmelCase   :					str        =    model(**_a       )

      # verify the logits
      _lowerCAmelCase   :					List[Any]        =    tf.TensorShape((1, 1_0_0_0)       )
      self.assertEqual(outputs.logits.shape     ,						_a       )

      _lowerCAmelCase   :					Optional[int]        =    tf.constant([-11.1069, -9.7877, -8.3777]       )

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









from pathlib import PurePosixPath
from typing import Optional

import fsspec
from fsspec import AbstractFileSystem
from huggingface_hub.hf_api import DatasetInfo

from ..utils.file_utils import get_authentication_headers_for_url
from ..utils.hub import hf_hub_url





class A__    ( A ):



 """simple docstring"""







 _lowercase     :					List[str]      =						''''''
 _lowercase     :					Optional[Any]      =						'''hf-legacy'''  # "hf://"" is reserved for hffs

 def __init__(		self :	Dict     ,						A_ :	Optional[DatasetInfo] = None     ,						A_ :	Optional[str] = None     ,						**A_ :	int     ,						):






      '''simple docstring'''




      super().__init__(self     ,						**A_       )
      _lowerCAmelCase   :					Union[str, Any]        =    repo_info
      _lowerCAmelCase   :					Optional[int]        =    token
      _lowerCAmelCase   :					str        =    None

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      if self.dir_cache is None:
           _lowerCAmelCase   :					int        =    {}
           for hf_file in self.repo_info.siblings:
                # TODO(QL): add sizes
                _lowerCAmelCase   :					Optional[int]        =    {
                    "name": hf_file.rfilename,
                    "size": None,
                    "type": "file",
                }
                self.dir_cache.update(
                    {
                        str(A_       ): {"name": str(A_       ), "size": None, "type": "directory"}
                        for d in list(PurePosixPath(hf_file.rfilename       ).parents       )[:-1]
                    }       )

 def    __magic_name__       (		self :	Dict     ,						A_ :	str     ,						A_ :	str = "rb"     ,						**A_ :	Optional[int]     ,						):






      '''simple docstring'''




      if not isinstance(self.repo_info     ,						A_       ):
           raise NotImplementedError(F'''Open is only implemented for dataset repositories, but got {self.repo_info}'''       )
      _lowerCAmelCase   :					str        =    hf_hub_url(self.repo_info.id     ,						A_     ,						revision=self.repo_info.sha       )
      return fsspec.open(
          A_     ,						mode=A_     ,						headers=get_authentication_headers_for_url(A_     ,						use_auth_token=self.token       )     ,						client_kwargs={"trust_env": True}     ,						).open()

 def    __magic_name__       (		self :	Union[str, Any]     ,						A_ :	List[Any]     ,						**A_ :	str       ):






      '''simple docstring'''




      self._get_dirs()
      _lowerCAmelCase   :					Optional[int]        =    self._strip_protocol(A_       )
      if path in self.dir_cache:
           return self.dir_cache[path]
      else:
           raise FileNotFoundError(A_       )


 def    __magic_name__       (		self :	Any     ,						A_ :	str     ,						A_ :	Any=False     ,						**A_ :	Dict       ):






      '''simple docstring'''




      self._get_dirs()
      _lowerCAmelCase   :					Dict        =    PurePosixPath(path.strip("/"       )       )
      _lowerCAmelCase   :					str        =    {}
      for p, f in self.dir_cache.items():
           _lowerCAmelCase   :					List[str]        =    PurePosixPath(p.strip("/"       )       )
           _lowerCAmelCase   :					Tuple        =    p.parent
           if root == path:
                _lowerCAmelCase   :					Union[str, Any]        =    f
      _lowerCAmelCase   :					List[str]        =    list(paths.values()       )
      if detail:
           return out
      else:
           return sorted(f["name"] for f in out       )






