

"""simple docstring"""






import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...utils import CONFIG_NAME, FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


_lowerCAmelCase						=		logging.get_logger(__name__)

_lowerCAmelCase						=		OrderedDict(
    [
        ("""audio-spectrogram-transformer""", """ASTFeatureExtractor"""),
        ("""beit""", """BeitFeatureExtractor"""),
        ("""chinese_clip""", """ChineseCLIPFeatureExtractor"""),
        ("""clap""", """ClapFeatureExtractor"""),
        ("""clip""", """CLIPFeatureExtractor"""),
        ("""clipseg""", """ViTFeatureExtractor"""),
        ("""conditional_detr""", """ConditionalDetrFeatureExtractor"""),
        ("""convnext""", """ConvNextFeatureExtractor"""),
        ("""cvt""", """ConvNextFeatureExtractor"""),
        ("""data2vec-audio""", """Wav2Vec2FeatureExtractor"""),
        ("""data2vec-vision""", """BeitFeatureExtractor"""),
        ("""deformable_detr""", """DeformableDetrFeatureExtractor"""),
        ("""deit""", """DeiTFeatureExtractor"""),
        ("""detr""", """DetrFeatureExtractor"""),
        ("""dinat""", """ViTFeatureExtractor"""),
        ("""donut-swin""", """DonutFeatureExtractor"""),
        ("""dpt""", """DPTFeatureExtractor"""),
        ("""encodec""", """EncodecFeatureExtractor"""),
        ("""flava""", """FlavaFeatureExtractor"""),
        ("""glpn""", """GLPNFeatureExtractor"""),
        ("""groupvit""", """CLIPFeatureExtractor"""),
        ("""hubert""", """Wav2Vec2FeatureExtractor"""),
        ("""imagegpt""", """ImageGPTFeatureExtractor"""),
        ("""layoutlmv2""", """LayoutLMv2FeatureExtractor"""),
        ("""layoutlmv3""", """LayoutLMv3FeatureExtractor"""),
        ("""levit""", """LevitFeatureExtractor"""),
        ("""maskformer""", """MaskFormerFeatureExtractor"""),
        ("""mctct""", """MCTCTFeatureExtractor"""),
        ("""mobilenet_v1""", """MobileNetV1FeatureExtractor"""),
        ("""mobilenet_v2""", """MobileNetV2FeatureExtractor"""),
        ("""mobilevit""", """MobileViTFeatureExtractor"""),
        ("""nat""", """ViTFeatureExtractor"""),
        ("""owlvit""", """OwlViTFeatureExtractor"""),
        ("""perceiver""", """PerceiverFeatureExtractor"""),
        ("""poolformer""", """PoolFormerFeatureExtractor"""),
        ("""regnet""", """ConvNextFeatureExtractor"""),
        ("""resnet""", """ConvNextFeatureExtractor"""),
        ("""segformer""", """SegformerFeatureExtractor"""),
        ("""sew""", """Wav2Vec2FeatureExtractor"""),
        ("""sew-d""", """Wav2Vec2FeatureExtractor"""),
        ("""speech_to_text""", """Speech2TextFeatureExtractor"""),
        ("""speecht5""", """SpeechT5FeatureExtractor"""),
        ("""swiftformer""", """ViTFeatureExtractor"""),
        ("""swin""", """ViTFeatureExtractor"""),
        ("""swinv2""", """ViTFeatureExtractor"""),
        ("""table-transformer""", """DetrFeatureExtractor"""),
        ("""timesformer""", """VideoMAEFeatureExtractor"""),
        ("""tvlt""", """TvltFeatureExtractor"""),
        ("""unispeech""", """Wav2Vec2FeatureExtractor"""),
        ("""unispeech-sat""", """Wav2Vec2FeatureExtractor"""),
        ("""van""", """ConvNextFeatureExtractor"""),
        ("""videomae""", """VideoMAEFeatureExtractor"""),
        ("""vilt""", """ViltFeatureExtractor"""),
        ("""vit""", """ViTFeatureExtractor"""),
        ("""vit_mae""", """ViTFeatureExtractor"""),
        ("""vit_msn""", """ViTFeatureExtractor"""),
        ("""wav2vec2""", """Wav2Vec2FeatureExtractor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2FeatureExtractor"""),
        ("""wavlm""", """Wav2Vec2FeatureExtractor"""),
        ("""whisper""", """WhisperFeatureExtractor"""),
        ("""xclip""", """CLIPFeatureExtractor"""),
        ("""yolos""", """YolosFeatureExtractor"""),
    ]
)

_lowerCAmelCase						=		_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)

def 		lowerCamelCase__		(					_lowerCamelCase   ):

    '''simple docstring'''



    for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
        if class_name in extractors:
            _lowerCAmelCase       :   Any  =    model_type_to_module_name(_lowerCamelCase   )

            _lowerCAmelCase       :   int  =    importlib.import_module(f""".{module_name}""" ,   'transformers.models'   )
            try:
                return getattr(_lowerCamelCase ,   _lowerCamelCase   )
            except AttributeError:
                continue

    for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
        if getattr(_lowerCamelCase ,   '__name__' ,   _lowerCamelCase   ) == class_name:
            return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
    _lowerCAmelCase       :   Optional[int]  =    importlib.import_module('transformers'   )
    if hasattr(_lowerCamelCase ,   _lowerCamelCase   ):
        return getattr(_lowerCamelCase ,   _lowerCamelCase   )

    return None

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase = None ,   _lowerCamelCase = False ,   _lowerCamelCase = False ,   _lowerCamelCase = None ,   _lowerCamelCase = None ,   _lowerCamelCase = None ,   _lowerCamelCase = False ,   **_lowerCamelCase ,   ):

    '''simple docstring'''



    _lowerCAmelCase       :   Tuple  =    get_file_from_repo(
        _lowerCamelCase ,   _lowerCamelCase ,   cache_dir=_lowerCamelCase ,   force_download=_lowerCamelCase ,   resume_download=_lowerCamelCase ,   proxies=_lowerCamelCase ,   use_auth_token=_lowerCamelCase ,   revision=_lowerCamelCase ,   local_files_only=_lowerCamelCase ,   )
    if resolved_config_file is None:
        logger.info(
            'Could not locate the feature extractor configuration file, will try to use the model config instead.'   )
        return {}

    with open(_lowerCamelCase ,   encoding='utf-8'   ) as reader:
        return json.load(_lowerCamelCase   )







class 	__UpperCamelCase    :

  def __init__(		self      ):
      '''simple docstring'''

      raise EnvironmentError(
          'AutoFeatureExtractor is designed to be instantiated '
          'using the `AutoFeatureExtractor.from_pretrained(pretrained_model_name_or_path)` method.'      )

  @classmethod
  @replace_list_option_in_docstrings(_A      )
  def __lowerCamelCase		(		cls    ,_A    ,**_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   int  =    kwargs.pop('config'    ,_A      )
      _lowerCAmelCase       :   Dict  =    kwargs.pop('trust_remote_code'    ,_A      )
      _lowerCAmelCase       :   str  =    True

      _lowerCAmelCase,					_lowerCAmelCase       :   str  =    FeatureExtractionMixin.get_feature_extractor_dict(_A    ,**_A      )
      _lowerCAmelCase       :   List[Any]  =    config_dict.get('feature_extractor_type'    ,_A      )
      _lowerCAmelCase       :   Tuple  =    None
      if "AutoFeatureExtractor" in config_dict.get('auto_map'    ,{}      ):
          _lowerCAmelCase       :   Union[str, Any]  =    config_dict['auto_map']['AutoFeatureExtractor']

      # If we don't find the feature extractor class in the feature extractor config, let's try the model config.
      if feature_extractor_class is None and feature_extractor_auto_map is None:
          if not isinstance(_A    ,_A      ):
              _lowerCAmelCase       :   Any  =    AutoConfig.from_pretrained(_A    ,**_A      )
          # It could be in `config.feature_extractor_type``
          _lowerCAmelCase       :   Optional[int]  =    getattr(_A    ,'feature_extractor_type'    ,_A      )
          if hasattr(_A    ,'auto_map'      ) and "AutoFeatureExtractor" in config.auto_map:
              _lowerCAmelCase       :   Optional[Any]  =    config.auto_map['AutoFeatureExtractor']

      if feature_extractor_class is not None:
          _lowerCAmelCase       :   Optional[Any]  =    feature_extractor_class_from_name(_A      )

      _lowerCAmelCase       :   Optional[int]  =    feature_extractor_auto_map is not None
      _lowerCAmelCase       :   str  =    feature_extractor_class is not None or type(_A      ) in FEATURE_EXTRACTOR_MAPPING
      _lowerCAmelCase       :   Tuple  =    resolve_trust_remote_code(
          _A    ,_A    ,_A    ,_A      )

      if has_remote_code and trust_remote_code:
          _lowerCAmelCase       :   List[Any]  =    get_class_from_dynamic_module(
              _A    ,_A    ,**_A      )
          _lowerCAmelCase       :   List[Any]  =    kwargs.pop('code_revision'    ,_A      )
          if os.path.isdir(_A      ):
              feature_extractor_class.register_for_auto_class()
          return feature_extractor_class.from_dict(_A    ,**_A      )
      elif feature_extractor_class is not None:
          return feature_extractor_class.from_dict(_A    ,**_A      )
      # Last try: we use the FEATURE_EXTRACTOR_MAPPING.
      elif type(_A      ) in FEATURE_EXTRACTOR_MAPPING:
          _lowerCAmelCase       :   List[str]  =    FEATURE_EXTRACTOR_MAPPING[type(_A      )]
          return feature_extractor_class.from_dict(_A    ,**_A      )

      raise ValueError(
          F"""Unrecognized feature extractor in {pretrained_model_name_or_path}. Should have a """
          F"""`feature_extractor_type` key in its {FEATURE_EXTRACTOR_NAME} of {CONFIG_NAME}, or one of the following """
          F"""`model_type` keys in its {CONFIG_NAME}: {', '.join(c for c in FEATURE_EXTRACTOR_MAPPING_NAMES.keys()      )}"""      )







  @staticmethod
  def __lowerCamelCase		(		_A    ,_A      ):
      '''simple docstring'''

      FEATURE_EXTRACTOR_MAPPING.register(_A    ,_A      )








"""simple docstring"""






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

  def __init__(		self    ,_A    ,_A=3    ,_A=32    ,_A=3    ,_A=10    ,_A=[10, 20, 30, 40]    ,_A=[1, 1, 2, 1]    ,_A=True    ,_A=True    ,_A="relu"    ,_A=3    ,_A=None    ,):
      '''simple docstring'''

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

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

      _lowerCAmelCase       :   Union[str, Any]  =    self.get_config()

      return config, pixel_values, labels

  def __lowerCamelCase		(		self      ):
      '''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 __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    TFResNetModel(config=_A      )
      _lowerCAmelCase       :   List[str]  =    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 __lowerCamelCase		(		self    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Any  =    self.num_labels
      _lowerCAmelCase       :   Dict  =    TFResNetForImageClassification(_A      )
      _lowerCAmelCase       :   int  =    model(_A    ,labels=_A      )
      self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.num_labels)      )







  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







@require_tf
class 	__UpperCamelCase    (    a__							,							a__							,							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 __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[str]  =    TFResNetModelTester(self      )
      _lowerCAmelCase       :   List[str]  =    ConfigTester(self    ,config_class=_A    ,has_text_modality=_A      )

  def __lowerCamelCase		(		self      ):
      '''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 __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return

  @unittest.skip(reason='ResNet does not use inputs_embeds'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  @unittest.skip(reason='ResNet does not support input and output embeddings'      )
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      pass

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

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

          _lowerCAmelCase       :   str  =    ['pixel_values']
          self.assertListEqual(arg_names[:1]    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      def check_hidden_states_output(_A    ,_A    ,_A      ):
          _lowerCAmelCase       :   int  =    model_class(_A      )
          _lowerCAmelCase       :   int  =    model(**self._prepare_for_class(_A    ,_A      )      )

          _lowerCAmelCase       :   Dict  =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

          _lowerCAmelCase       :   int  =    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,					_lowerCAmelCase       :   List[str]  =    self.model_tester.prepare_config_and_inputs_for_common()
      _lowerCAmelCase       :   Any  =    ['basic', 'bottleneck']
      for model_class in self.all_model_classes:
          for layer_type in layers_type:
              _lowerCAmelCase       :   Optional[int]  =    layer_type
              _lowerCAmelCase       :   Tuple  =    True
              check_hidden_states_output(_A    ,_A    ,_A      )

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

              check_hidden_states_output(_A    ,_A    ,_A      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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





def 		lowerCamelCase__		(					):

    '''simple docstring'''



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







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

  @cached_property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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







  @slow
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

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

      _lowerCAmelCase       :   Tuple  =    self.default_image_processor
      _lowerCAmelCase       :   Optional[Any]  =    prepare_img()
      _lowerCAmelCase       :   int  =    image_processor(images=_A    ,return_tensors='tf'      )

      # forward pass
      _lowerCAmelCase       :   int  =    model(**_A      )

      # verify the logits
      _lowerCAmelCase       :   Optional[Any]  =    tf.TensorShape((1, 1000)      )
      self.assertEqual(outputs.logits.shape    ,_A      )

      _lowerCAmelCase       :   Any  =    tf.constant([-1_1.1_0_6_9, -9.7_8_7_7, -8.3_7_7_7]      )

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





