'''simple docstring'''




from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


__UpperCAmelCase					=logging.get_logger(__name__)

# General docstring
__UpperCAmelCase					='ResNetConfig'

# Base docstring
__UpperCAmelCase					='microsoft/resnet-50'
__UpperCAmelCase					=[1, 2_0_4_8, 7, 7]

# Image classification docstring
__UpperCAmelCase					='microsoft/resnet-50'
__UpperCAmelCase					='tiger cat'

__UpperCAmelCase					=[
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]




class        a__ (  nn.Module					):






     def __init__(					self						:						Union[str, Any]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 3    ,							a						:						int = 1    ,							a						:						str = "relu"       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    nn.Convad(
             UpperCamelCase__    ,							UpperCamelCase__    ,							kernel_size=UpperCamelCase__    ,							stride=UpperCamelCase__    ,							padding=kernel_size // 2    ,							bias=UpperCamelCase__       )
         __lowerCamelCase            =    nn.BatchNormad(UpperCamelCase__       )
         __lowerCamelCase            =    ACTaFN[activation] if activation is not None else nn.Identity()






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    self.convolution(UpperCamelCase__       )
         __lowerCamelCase            =    self.normalization(UpperCamelCase__       )
         __lowerCamelCase            =    self.activation(UpperCamelCase__       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						Tuple    ,							a						:						ResNetConfig       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    ResNetConvLayer(
             config.num_channels    ,							config.embedding_size    ,							kernel_size=7    ,							stride=2    ,							activation=config.hidden_act       )
         __lowerCamelCase            =    nn.MaxPoolad(kernel_size=3    ,							stride=2    ,							padding=1       )
         __lowerCamelCase            =    config.num_channels






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    pixel_values.shape[1]
         if num_channels != self.num_channels:
             raise ValueError(
                 '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''       )
         __lowerCamelCase            =    self.embedder(UpperCamelCase__       )
         __lowerCamelCase            =    self.pooler(UpperCamelCase__       )
         return embedding




class        a__ (  nn.Module					):






     def __init__(					self						:						List[str]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 2       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    nn.Convad(UpperCamelCase__    ,							UpperCamelCase__    ,							kernel_size=1    ,							stride=UpperCamelCase__    ,							bias=UpperCamelCase__       )
         __lowerCamelCase            =    nn.BatchNormad(UpperCamelCase__       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    self.convolution(UpperCamelCase__       )
         __lowerCamelCase            =    self.normalization(UpperCamelCase__       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						Union[str, Any]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 1    ,							a						:						str = "relu"       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    in_channels != out_channels or stride != 1
         __lowerCamelCase            =    (
             ResNetShortCut(UpperCamelCase__    ,							UpperCamelCase__    ,							stride=UpperCamelCase__       ) if should_apply_shortcut else nn.Identity()
         )
         __lowerCamelCase            =    nn.Sequential(
             ResNetConvLayer(UpperCamelCase__    ,							UpperCamelCase__    ,							stride=UpperCamelCase__       )    ,							ResNetConvLayer(UpperCamelCase__    ,							UpperCamelCase__    ,							activation=UpperCamelCase__       )    ,							)
         __lowerCamelCase            =    ACTaFN[activation]






     def   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						List[str]       ):





         """simple docstring"""



         __lowerCamelCase            =    hidden_state
         __lowerCamelCase            =    self.layer(UpperCamelCase__       )
         __lowerCamelCase            =    self.shortcut(UpperCamelCase__       )
         hidden_state += residual
         __lowerCamelCase            =    self.activation(UpperCamelCase__       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						List[str]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 1    ,							a						:						str = "relu"    ,							a						:						int = 4       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    in_channels != out_channels or stride != 1
         __lowerCamelCase            =    out_channels // reduction
         __lowerCamelCase            =    (
             ResNetShortCut(UpperCamelCase__    ,							UpperCamelCase__    ,							stride=UpperCamelCase__       ) if should_apply_shortcut else nn.Identity()
         )
         __lowerCamelCase            =    nn.Sequential(
             ResNetConvLayer(UpperCamelCase__    ,							UpperCamelCase__    ,							kernel_size=1       )    ,							ResNetConvLayer(UpperCamelCase__    ,							UpperCamelCase__    ,							stride=UpperCamelCase__       )    ,							ResNetConvLayer(UpperCamelCase__    ,							UpperCamelCase__    ,							kernel_size=1    ,							activation=UpperCamelCase__       )    ,							)
         __lowerCamelCase            =    ACTaFN[activation]






     def   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]    ,							a						:						Tuple       ):





         """simple docstring"""



         __lowerCamelCase            =    hidden_state
         __lowerCamelCase            =    self.layer(UpperCamelCase__       )
         __lowerCamelCase            =    self.shortcut(UpperCamelCase__       )
         hidden_state += residual
         __lowerCamelCase            =    self.activation(UpperCamelCase__       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						Any    ,							a						:						ResNetConfig    ,							a						:						int    ,							a						:						int    ,							a						:						int = 2    ,							a						:						int = 2    ,							):





         """simple docstring"""



         super().__init__()

         __lowerCamelCase            =    ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

         __lowerCamelCase            =    nn.Sequential(
             # downsampling is done in the first layer with stride of 2
             layer(UpperCamelCase__    ,							UpperCamelCase__    ,							stride=UpperCamelCase__    ,							activation=config.hidden_act       )    ,							*[layer(UpperCamelCase__    ,							UpperCamelCase__    ,							activation=config.hidden_act       ) for _ in range(depth - 1       )]    ,							)






     def   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    input
         for layer in self.layers:
             __lowerCamelCase            =    layer(UpperCamelCase__       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						str    ,							a						:						ResNetConfig       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    nn.ModuleList([]       )
         # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
         self.stages.append(
             ResNetStage(
                 UpperCamelCase__    ,							config.embedding_size    ,							config.hidden_sizes[0]    ,							stride=2 if config.downsample_in_first_stage else 1    ,							depth=config.depths[0]    ,							)       )
         __lowerCamelCase            =    zip(config.hidden_sizes    ,							config.hidden_sizes[1:]       )
         for (in_channels, out_channels), depth in zip(UpperCamelCase__    ,							config.depths[1:]       ):
             self.stages.append(ResNetStage(UpperCamelCase__    ,							UpperCamelCase__    ,							UpperCamelCase__    ,							depth=UpperCamelCase__       )       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Tensor    ,							a						:						bool = False    ,							a						:						bool = True       ):





         """simple docstring"""



         __lowerCamelCase            =    () if output_hidden_states else None

         for stage_module in self.stages:
             if output_hidden_states:
                 __lowerCamelCase            =    hidden_states + (hidden_state,)

             __lowerCamelCase            =    stage_module(UpperCamelCase__       )

         if output_hidden_states:
             __lowerCamelCase            =    hidden_states + (hidden_state,)

         if not return_dict:
             return tuple(v for v in [hidden_state, hidden_states] if v is not None       )

         return BaseModelOutputWithNoAttention(
             last_hidden_state=UpperCamelCase__    ,							hidden_states=UpperCamelCase__    ,							)




class        a__ (  _A					):
     lowerCamelCase    :	Tuple				=ResNetConfig
     lowerCamelCase    :	int				="resnet"
     lowerCamelCase    :	int				="pixel_values"
     lowerCamelCase    :	Tuple				=True






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple    ,							a						:						List[Any]       ):





         """simple docstring"""



         if isinstance(UpperCamelCase__    ,							nn.Convad       ):
             nn.init.kaiming_normal_(module.weight    ,							mode='''fan_out'''    ,							nonlinearity='''relu'''       )
         elif isinstance(UpperCamelCase__    ,							(nn.BatchNormad, nn.GroupNorm)       ):
             nn.init.constant_(module.weight    ,							1       )
             nn.init.constant_(module.bias    ,							0       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Tuple    ,							a						:						Union[str, Any]=False       ):





         """simple docstring"""



         if isinstance(UpperCamelCase__    ,							UpperCamelCase__       ):
             __lowerCamelCase            =    value
__UpperCAmelCase					=R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

__UpperCAmelCase					=R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'




@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."				,  _A				,  )
class        a__ (  _A					):






     def __init__(					self						:						Optional[int]    ,							a						:						List[str]       ):





         """simple docstring"""



         super().__init__(UpperCamelCase__       )
         __lowerCamelCase            =    config
         __lowerCamelCase            =    ResNetEmbeddings(UpperCamelCase__       )
         __lowerCamelCase            =    ResNetEncoder(UpperCamelCase__       )
         __lowerCamelCase            =    nn.AdaptiveAvgPoolad((1, 1)       )
         # Initialize weights and apply final processing
         self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase__       )
     @add_code_sample_docstrings(
         checkpoint=_CHECKPOINT_FOR_DOC    ,							output_type=UpperCamelCase__    ,							config_class=_CONFIG_FOR_DOC    ,							modality='''vision'''    ,							expected_output=_EXPECTED_OUTPUT_SHAPE    ,							)
     def   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						Tensor    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None       ):





         """simple docstring"""



         __lowerCamelCase            =    (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         __lowerCamelCase            =    return_dict if return_dict is not None else self.config.use_return_dict

         __lowerCamelCase            =    self.embedder(UpperCamelCase__       )

         __lowerCamelCase            =    self.encoder(
             UpperCamelCase__    ,							output_hidden_states=UpperCamelCase__    ,							return_dict=UpperCamelCase__       )

         __lowerCamelCase            =    encoder_outputs[0]

         __lowerCamelCase            =    self.pooler(UpperCamelCase__       )

         if not return_dict:
             return (last_hidden_state, pooled_output) + encoder_outputs[1:]

         return BaseModelOutputWithPoolingAndNoAttention(
             last_hidden_state=UpperCamelCase__    ,							pooler_output=UpperCamelCase__    ,							hidden_states=encoder_outputs.hidden_states    ,							)




@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "				,  _A				,  )
class        a__ (  _A					):






     def __init__(					self						:						Tuple    ,							a						:						Optional[int]       ):





         """simple docstring"""



         super().__init__(UpperCamelCase__       )
         __lowerCamelCase            =    config.num_labels
         __lowerCamelCase            =    ResNetModel(UpperCamelCase__       )
         # classification head
         __lowerCamelCase            =    nn.Sequential(
             nn.Flatten()    ,							nn.Linear(config.hidden_sizes[-1]    ,							config.num_labels       ) if config.num_labels > 0 else nn.Identity()    ,							)
         # initialize weights and apply final processing
         self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase__       )
     @add_code_sample_docstrings(
         checkpoint=_IMAGE_CLASS_CHECKPOINT    ,							output_type=UpperCamelCase__    ,							config_class=_CONFIG_FOR_DOC    ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT    ,							)
     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Optional[torch.FloatTensor] = None    ,							a						:						Optional[torch.LongTensor] = None    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None    ,							):





         """simple docstring"""



         __lowerCamelCase            =    return_dict if return_dict is not None else self.config.use_return_dict

         __lowerCamelCase            =    self.resnet(UpperCamelCase__    ,							output_hidden_states=UpperCamelCase__    ,							return_dict=UpperCamelCase__       )

         __lowerCamelCase            =    outputs.pooler_output if return_dict else outputs[1]

         __lowerCamelCase            =    self.classifier(UpperCamelCase__       )

         __lowerCamelCase            =    None

         if labels is not None:
             if self.config.problem_type is None:
                 if self.num_labels == 1:
                     __lowerCamelCase            =    '''regression'''
                 elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                     __lowerCamelCase            =    '''single_label_classification'''
                 else:
                     __lowerCamelCase            =    '''multi_label_classification'''
             if self.config.problem_type == "regression":
                 __lowerCamelCase            =    MSELoss()
                 if self.num_labels == 1:
                     __lowerCamelCase            =    loss_fct(logits.squeeze()    ,							labels.squeeze()       )
                 else:
                     __lowerCamelCase            =    loss_fct(UpperCamelCase__    ,							UpperCamelCase__       )
             elif self.config.problem_type == "single_label_classification":
                 __lowerCamelCase            =    CrossEntropyLoss()
                 __lowerCamelCase            =    loss_fct(logits.view(-1    ,							self.num_labels       )    ,							labels.view(-1       )       )
             elif self.config.problem_type == "multi_label_classification":
                 __lowerCamelCase            =    BCEWithLogitsLoss()
                 __lowerCamelCase            =    loss_fct(UpperCamelCase__    ,							UpperCamelCase__       )

         if not return_dict:
             __lowerCamelCase            =    (logits,) + outputs[2:]
             return (loss,) + output if loss is not None else output

         return ImageClassifierOutputWithNoAttention(loss=UpperCamelCase__    ,							logits=UpperCamelCase__    ,							hidden_states=outputs.hidden_states       )




@add_start_docstrings(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "				,  _A				,  )
class        a__ (  _A				,  _A					):






     def __init__(					self						:						List[str]    ,							a						:						Optional[Any]       ):





         """simple docstring"""



         super().__init__(UpperCamelCase__       )
         super()._init_backbone(UpperCamelCase__       )

         __lowerCamelCase            =    [config.embedding_size] + config.hidden_sizes
         __lowerCamelCase            =    ResNetEmbeddings(UpperCamelCase__       )
         __lowerCamelCase            =    ResNetEncoder(UpperCamelCase__       )

         # initialize weights and apply final processing
         self.post_init()






     @add_start_docstrings_to_model_forward(UpperCamelCase__       )
     @replace_return_docstrings(output_type=UpperCamelCase__    ,							config_class=_CONFIG_FOR_DOC       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]    ,							a						:						Tensor    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None       ):





         """simple docstring"""



         __lowerCamelCase            =    return_dict if return_dict is not None else self.config.use_return_dict
         __lowerCamelCase            =    (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )

         __lowerCamelCase            =    self.embedder(UpperCamelCase__       )

         __lowerCamelCase            =    self.encoder(UpperCamelCase__    ,							output_hidden_states=UpperCamelCase__    ,							return_dict=UpperCamelCase__       )

         __lowerCamelCase            =    outputs.hidden_states

         __lowerCamelCase            =    ()
         for idx, stage in enumerate(self.stage_names       ):
             if stage in self.out_features:
                 feature_maps += (hidden_states[idx],)

         if not return_dict:
             __lowerCamelCase            =    (feature_maps,)
             if output_hidden_states:
                 output += (outputs.hidden_states,)
             return output

         return BackboneOutput(
             feature_maps=UpperCamelCase__    ,							hidden_states=outputs.hidden_states if output_hidden_states else None    ,							attentions=UpperCamelCase__    ,							)


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     :	List[str]       			=  logging.get_logger(__name__)

__lowerCAmelCase     :	List[Any]       			=  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     :	Optional[Any]       			=  _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)

def a__       (			A_   ):






  '''simple docstring'''





  for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
    if class_name in extractors:
      __magic_name__								=			model_type_to_module_name(A_   )

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

  for _, extractor in FEATURE_EXTRACTOR_MAPPING._extra_content.items():
    if getattr(A_,	"""__name__""",	A_   ) == 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.
  __magic_name__								=			importlib.import_module("""transformers"""   )
  if hasattr(A_,	A_   ):
    return getattr(A_,	A_   )

  return None

def a__       (			A_,	A_ = None,	A_ = False,	A_ = False,	A_ = None,	A_ = None,	A_ = None,	A_ = False,	**A_,	):






  '''simple docstring'''





  __magic_name__								=			get_file_from_repo(
      A_,	A_,	cache_dir=A_,	force_download=A_,	resume_download=A_,	proxies=A_,	use_auth_token=A_,	revision=A_,	local_files_only=A_,	)
  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(A_,	encoding="""utf-8"""   ) as reader:
    return json.load(A_   )





class 			UpperCAmelCase_     :


  '''simple docstring'''







  def __init__(					self     :					Dict       )     ->      Optional[int]:







    """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(UpperCamelCase__       )
  def 				_lowercase				(					cls     :					Optional[int]     ,				UpperCamelCase__     :					Any     ,				**UpperCamelCase__     :					Optional[int]       )     ->      str:







    """simple docstring"""






    __magic_name__								=			kwargs.pop("""config"""     ,				UpperCamelCase__       )
    __magic_name__								=			kwargs.pop("""trust_remote_code"""     ,				UpperCamelCase__       )
    __magic_name__								=			True

    __magic_name__	,       __magic_name__								=			FeatureExtractionMixin.get_feature_extractor_dict(UpperCamelCase__     ,				**UpperCamelCase__       )
    __magic_name__								=			config_dict.get("""feature_extractor_type"""     ,				UpperCamelCase__       )
    __magic_name__								=			None
    if "AutoFeatureExtractor" in config_dict.get("""auto_map"""     ,				{}       ):
      __magic_name__								=			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(UpperCamelCase__     ,				UpperCamelCase__       ):
        __magic_name__								=			AutoConfig.from_pretrained(UpperCamelCase__     ,				**UpperCamelCase__       )
      # It could be in `config.feature_extractor_type``
      __magic_name__								=			getattr(UpperCamelCase__     ,				"""feature_extractor_type"""     ,				UpperCamelCase__       )
      if hasattr(UpperCamelCase__     ,				"""auto_map"""       ) and "AutoFeatureExtractor" in config.auto_map:
        __magic_name__								=			config.auto_map["""AutoFeatureExtractor"""]

    if feature_extractor_class is not None:
      __magic_name__								=			feature_extractor_class_from_name(UpperCamelCase__       )

    __magic_name__								=			feature_extractor_auto_map is not None
    __magic_name__								=			feature_extractor_class is not None or type(UpperCamelCase__       ) in FEATURE_EXTRACTOR_MAPPING
    __magic_name__								=			resolve_trust_remote_code(
        UpperCamelCase__     ,				UpperCamelCase__     ,				UpperCamelCase__     ,				UpperCamelCase__       )

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

    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 				_lowercase				(					UpperCamelCase__     :					Any     ,				UpperCamelCase__     :					Optional[Any]       )     ->      Dict:







    """simple docstring"""






    FEATURE_EXTRACTOR_MAPPING.register(UpperCamelCase__     ,				UpperCamelCase__       )

