
"""simple docstring"""


from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


__A       						=       logging.get_logger(__name__)

# General docstring
__A       						=       'ResNetConfig'

# Base docstring
__A       						=       'microsoft/resnet-50'
__A       						=       [1, 2048, 7, 7]

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

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







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = 3     ,     __UpperCAmelCase = 1     ,     __UpperCAmelCase = "relu"     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=kernel_size // 2
				_lowerCAmelCase								=tf.keras.layers.ConvaD(
				    __UpperCAmelCase     ,     kernel_size=__UpperCAmelCase     ,     strides=__UpperCAmelCase     ,     padding="""valid"""     ,     use_bias=__UpperCAmelCase     ,     name="""convolution"""  )
				# Use same default momentum and epsilon as PyTorch equivalent
				_lowerCAmelCase								=tf.keras.layers.BatchNormalization(epsilon=1e-5     ,     momentum=0.9     ,     name="""normalization"""  )
				_lowerCAmelCase								=ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("""linear"""  )



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase  ) ->     tf.Tensor:
				# Pad to match that done in the PyTorch Conv2D model
				_lowerCAmelCase								=_lowerCAmelCase								=(self.pad_value, self.pad_value)
				_lowerCAmelCase								=tf.pad(__UpperCAmelCase     ,     [(0, 0), height_pad, width_pad, (0, 0)]  )
				_lowerCAmelCase								=self.conv(__UpperCAmelCase  )
				return hidden_state



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				_lowerCAmelCase								=self.convolution(__UpperCAmelCase  )
				_lowerCAmelCase								=self.normalization(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.activation(__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=TFResNetConvLayer(
				    config.embedding_size     ,     kernel_size=7     ,     stride=2     ,     activation=config.hidden_act     ,     name="""embedder"""     ,     )
				_lowerCAmelCase								=tf.keras.layers.MaxPoolaD(pool_size=3     ,     strides=2     ,     padding="""valid"""     ,     name="""pooler"""  )
				_lowerCAmelCase								=config.num_channels



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				_lowerCAmelCase						,							_lowerCAmelCase						,							_lowerCAmelCase						,							_lowerCAmelCase								=shape_list(__UpperCAmelCase  )
				if tf.executing_eagerly() and 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								=pixel_values
				_lowerCAmelCase								=self.embedder(__UpperCAmelCase  )
				_lowerCAmelCase								=tf.pad(__UpperCAmelCase     ,     [[0, 0], [1, 1], [1, 1], [0, 0]]  )
				_lowerCAmelCase								=self.pooler(__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = 2     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=tf.keras.layers.ConvaD(
				    __UpperCAmelCase     ,     kernel_size=1     ,     strides=__UpperCAmelCase     ,     use_bias=__UpperCAmelCase     ,     name="""convolution"""  )
				# Use same default momentum and epsilon as PyTorch equivalent
				_lowerCAmelCase								=tf.keras.layers.BatchNormalization(epsilon=1e-5     ,     momentum=0.9     ,     name="""normalization"""  )



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				_lowerCAmelCase								=x
				_lowerCAmelCase								=self.convolution(__UpperCAmelCase  )
				_lowerCAmelCase								=self.normalization(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase = 1     ,     __UpperCAmelCase = "relu"     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=in_channels != out_channels or stride != 1
				_lowerCAmelCase								=TFResNetConvLayer(__UpperCAmelCase     ,     stride=__UpperCAmelCase     ,     name="""layer.0"""  )
				_lowerCAmelCase								=TFResNetConvLayer(__UpperCAmelCase     ,     activation=__UpperCAmelCase     ,     name="""layer.1"""  )
				_lowerCAmelCase								=(
				    TFResNetShortCut(__UpperCAmelCase     ,     stride=__UpperCAmelCase     ,     name="""shortcut"""  )
				    if should_apply_shortcut
				    else tf.keras.layers.Activation("""linear"""     ,     name="""shortcut"""  )
				)
				_lowerCAmelCase								=ACTaFN[activation]



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				_lowerCAmelCase								=hidden_state
				_lowerCAmelCase								=self.conva(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.conva(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.shortcut(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				hidden_state += residual
				_lowerCAmelCase								=self.activation(__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase = 1     ,     __UpperCAmelCase = "relu"     ,     __UpperCAmelCase = 4     ,     **__UpperCAmelCase     ,     ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=in_channels != out_channels or stride != 1
				_lowerCAmelCase								=out_channels // reduction
				_lowerCAmelCase								=TFResNetConvLayer(__UpperCAmelCase     ,     kernel_size=1     ,     name="""layer.0"""  )
				_lowerCAmelCase								=TFResNetConvLayer(__UpperCAmelCase     ,     stride=__UpperCAmelCase     ,     name="""layer.1"""  )
				_lowerCAmelCase								=TFResNetConvLayer(__UpperCAmelCase     ,     kernel_size=1     ,     activation=__UpperCAmelCase     ,     name="""layer.2"""  )
				_lowerCAmelCase								=(
				    TFResNetShortCut(__UpperCAmelCase     ,     stride=__UpperCAmelCase     ,     name="""shortcut"""  )
				    if should_apply_shortcut
				    else tf.keras.layers.Activation("""linear"""     ,     name="""shortcut"""  )
				)
				_lowerCAmelCase								=ACTaFN[activation]



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				_lowerCAmelCase								=hidden_state
				_lowerCAmelCase								=self.conva(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.conva(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.conva(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				_lowerCAmelCase								=self.shortcut(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				hidden_state += residual
				_lowerCAmelCase								=self.activation(__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase = 2     ,     __UpperCAmelCase = 2     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )

				_lowerCAmelCase								=TFResNetBottleNeckLayer if config.layer_type == """bottleneck""" else TFResNetBasicLayer

				_lowerCAmelCase								=[layer(__UpperCAmelCase     ,     __UpperCAmelCase     ,     stride=__UpperCAmelCase     ,     activation=config.hidden_act     ,     name="""layers.0"""  )]
				layers += [
				    layer(__UpperCAmelCase     ,     __UpperCAmelCase     ,     activation=config.hidden_act     ,     name=f'''layers.{i + 1}'''  )
				    for i in range(depth - 1  )
				]
				_lowerCAmelCase								=layers



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False  ) ->     tf.Tensor:
				for layer in self.stage_layers:
					_lowerCAmelCase								=layer(__UpperCAmelCase     ,     training=__UpperCAmelCase  )
				return hidden_state







class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
				_lowerCAmelCase								=[
				    TFResNetStage(
				        __UpperCAmelCase     ,     config.embedding_size     ,     config.hidden_sizes[0]     ,     stride=2 if config.downsample_in_first_stage else 1     ,     depth=config.depths[0]     ,     name="""stages.0"""     ,     )
				]
				for i, (in_channels, out_channels, depth) in enumerate(
				    zip(config.hidden_sizes     ,     config.hidden_sizes[1:]     ,     config.depths[1:]  )  ):
					self.stages.append(TFResNetStage(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     depth=__UpperCAmelCase     ,     name=f'''stages.{i + 1}'''  )  )



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = False     ,     __UpperCAmelCase = True     ,     __UpperCAmelCase = False     ,     ) ->     TFBaseModelOutputWithNoAttention:
				_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     ,     training=__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 TFBaseModelOutputWithNoAttention(last_hidden_state=__UpperCAmelCase     ,     hidden_states=__UpperCAmelCase  )







class 		lowerCamelCase__					(					__magic_name__				):





			'''simple docstring'''
			lowerCamelCase  					=		ResNetConfig
			lowerCamelCase  					=		'''resnet'''
			lowerCamelCase  					=		'''pixel_values'''



			@property
			def 					_lowerCAmelCase		(							self  ) ->     Union[str, Any]:
				return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)     ,     dtype=tf.floataa  )}







__A       						=       r'\n    This model is a TensorFlow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular TensorFlow Module and refer to the TensorFlow 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n'


__A       						=       r'\n    Args:\n        pixel_values (`tf.Tensor` 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'







@keras_serializable
class 		lowerCamelCase__					(					tf.keras.layers.Layer				):





			'''simple docstring'''
			lowerCamelCase  					=		ResNetConfig



			def __init__(							self     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(**__UpperCAmelCase  )
				_lowerCAmelCase								=config
				_lowerCAmelCase								=TFResNetEmbeddings(__UpperCAmelCase     ,     name="""embedder"""  )
				_lowerCAmelCase								=TFResNetEncoder(__UpperCAmelCase     ,     name="""encoder"""  )
				_lowerCAmelCase								=tf.keras.layers.GlobalAveragePoolingaD(keepdims=__UpperCAmelCase  )



			@unpack_inputs
			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = False     ,     ) ->     Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
				_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

				# TF 2.0 image layers can't use NCHW format when running on CPU.
				# We transpose to NHWC format and then transpose back after the full forward pass.
				# (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
				_lowerCAmelCase								=tf.transpose(__UpperCAmelCase     ,     perm=[0, 2, 3, 1]  )
				_lowerCAmelCase								=self.embedder(__UpperCAmelCase     ,     training=__UpperCAmelCase  )

				_lowerCAmelCase								=self.encoder(
				    __UpperCAmelCase     ,     output_hidden_states=__UpperCAmelCase     ,     return_dict=__UpperCAmelCase     ,     training=__UpperCAmelCase  )

				_lowerCAmelCase								=encoder_outputs[0]

				_lowerCAmelCase								=self.pooler(__UpperCAmelCase  )

				# Transpose all the outputs to the NCHW format
				# (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
				_lowerCAmelCase								=tf.transpose(__UpperCAmelCase     ,     (0, 3, 1, 2)  )
				_lowerCAmelCase								=tf.transpose(__UpperCAmelCase     ,     (0, 3, 1, 2)  )
				_lowerCAmelCase								=()
				for hidden_state in encoder_outputs[1:]:
					_lowerCAmelCase								=hidden_states + tuple(tf.transpose(__UpperCAmelCase     ,     (0, 3, 1, 2)  ) for h in hidden_state  )

				if not return_dict:
					return (last_hidden_state, pooled_output) + hidden_states

				_lowerCAmelCase								=hidden_states if output_hidden_states else None

				return TFBaseModelOutputWithPoolingAndNoAttention(
				    last_hidden_state=__UpperCAmelCase     ,     pooler_output=__UpperCAmelCase     ,     hidden_states=__UpperCAmelCase     ,     )







@add_start_docstrings(
    '''The bare ResNet model outputting raw features without any specific head on top.''' ,	__magic_name__ ,	)
class 		lowerCamelCase__					(					__magic_name__				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(__UpperCAmelCase     ,     **__UpperCAmelCase  )
				_lowerCAmelCase								=TFResNetMainLayer(config=__UpperCAmelCase     ,     name="""resnet"""  )



			@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     ,     )
			@unpack_inputs
			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = False     ,     ) ->     Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
				_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.resnet(
				    pixel_values=__UpperCAmelCase     ,     output_hidden_states=__UpperCAmelCase     ,     return_dict=__UpperCAmelCase     ,     training=__UpperCAmelCase     ,     )
				return resnet_outputs







@add_start_docstrings(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    ''' ,	__magic_name__ ,	)
class 		lowerCamelCase__					(					__magic_name__ ,	__magic_name__				):





			'''simple docstring'''



			def __init__(							self     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     None:
				super().__init__(__UpperCAmelCase     ,     **__UpperCAmelCase  )
				_lowerCAmelCase								=config.num_labels
				_lowerCAmelCase								=TFResNetMainLayer(__UpperCAmelCase     ,     name="""resnet"""  )
				# classification head
				_lowerCAmelCase								=(
				    tf.keras.layers.Dense(config.num_labels     ,     name="""classifier.1"""  )
				    if config.num_labels > 0
				    else tf.keras.layers.Activation("""linear"""     ,     name="""classifier.1"""  )
				)



			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase  ) ->     tf.Tensor:
				_lowerCAmelCase								=tf.keras.layers.Flatten()(__UpperCAmelCase  )
				_lowerCAmelCase								=self.classifier_layer(__UpperCAmelCase  )
				return logits



			@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     ,     )
			@unpack_inputs
			def 					_lowerCAmelCase		(							self     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = None     ,     __UpperCAmelCase = False     ,     ) ->     Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:
				_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     ,     training=__UpperCAmelCase  )

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

				_lowerCAmelCase								=self.classifier(__UpperCAmelCase  )

				_lowerCAmelCase								=None if labels is None else self.hf_compute_loss(__UpperCAmelCase     ,     __UpperCAmelCase  )

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

				return TFImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase     ,     logits=__UpperCAmelCase     ,     hidden_states=outputs.hidden_states  )





"""simple docstring"""


import importlib
import inspect
import json
import os
from collections import OrderedDict

# 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 ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import 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,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


__A       						=       logging.get_logger(__name__)

__A       						=       OrderedDict(
    [
        ('align', 'AlignProcessor'),
        ('altclip', 'AltCLIPProcessor'),
        ('bark', 'BarkProcessor'),
        ('blip', 'BlipProcessor'),
        ('blip-2', 'Blip2Processor'),
        ('bridgetower', 'BridgeTowerProcessor'),
        ('chinese_clip', 'ChineseCLIPProcessor'),
        ('clap', 'ClapProcessor'),
        ('clip', 'CLIPProcessor'),
        ('clipseg', 'CLIPSegProcessor'),
        ('flava', 'FlavaProcessor'),
        ('git', 'GitProcessor'),
        ('groupvit', 'CLIPProcessor'),
        ('hubert', 'Wav2Vec2Processor'),
        ('instructblip', 'InstructBlipProcessor'),
        ('layoutlmv2', 'LayoutLMv2Processor'),
        ('layoutlmv3', 'LayoutLMv3Processor'),
        ('markuplm', 'MarkupLMProcessor'),
        ('mctct', 'MCTCTProcessor'),
        ('mgp-str', 'MgpstrProcessor'),
        ('oneformer', 'OneFormerProcessor'),
        ('owlvit', 'OwlViTProcessor'),
        ('pix2struct', 'Pix2StructProcessor'),
        ('sam', 'SamProcessor'),
        ('sew', 'Wav2Vec2Processor'),
        ('sew-d', 'Wav2Vec2Processor'),
        ('speech_to_text', 'Speech2TextProcessor'),
        ('speech_to_text_2', 'Speech2Text2Processor'),
        ('speecht5', 'SpeechT5Processor'),
        ('trocr', 'TrOCRProcessor'),
        ('tvlt', 'TvltProcessor'),
        ('unispeech', 'Wav2Vec2Processor'),
        ('unispeech-sat', 'Wav2Vec2Processor'),
        ('vilt', 'ViltProcessor'),
        ('vision-text-dual-encoder', 'VisionTextDualEncoderProcessor'),
        ('wav2vec2', 'Wav2Vec2Processor'),
        ('wav2vec2-conformer', 'Wav2Vec2Processor'),
        ('wavlm', 'Wav2Vec2Processor'),
        ('whisper', 'WhisperProcessor'),
        ('xclip', 'XCLIPProcessor'),
    ]
)

__A       						=       _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)



def     _lowerCamelCase(__UpperCamelCase       )				-> Optional[int]:
	for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
		if class_name in processors:
			_lowerCAmelCase								=model_type_to_module_name(__UpperCamelCase       )

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

	for processor in PROCESSOR_MAPPING._extra_content.values():
		if getattr(__UpperCamelCase    , """__name__"""    , __UpperCamelCase       ) == class_name:
			return processor

    # 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								=importlib.import_module("""transformers"""       )
	if hasattr(__UpperCamelCase    , __UpperCamelCase       ):
		return getattr(__UpperCamelCase    , __UpperCamelCase       )

	return None







class 		lowerCamelCase__					:





			'''simple docstring'''



			def __init__(							self  ) ->     str:
				raise EnvironmentError(
				    """AutoProcessor is designed to be instantiated """
				    """using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method."""  )



			@classmethod
			@replace_list_option_in_docstrings(__UpperCAmelCase  )
			def 					_lowerCAmelCase		(							cls     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  ) ->     Tuple:
				_lowerCAmelCase								=kwargs.pop("""config"""     ,     __UpperCAmelCase  )
				_lowerCAmelCase								=kwargs.pop("""trust_remote_code"""     ,     __UpperCAmelCase  )
				_lowerCAmelCase								=True

				_lowerCAmelCase								=None
				_lowerCAmelCase								=None

				# First, let's see if we have a preprocessor config.
				# Filter the kwargs for `get_file_from_repo`.
				_lowerCAmelCase								={
				    key: kwargs[key] for key in inspect.signature(__UpperCAmelCase  ).parameters.keys() if key in kwargs
				}
				# Let's start by checking whether the processor class is saved in an image processor
				_lowerCAmelCase								=get_file_from_repo(
				    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
				if preprocessor_config_file is not None:
					_lowerCAmelCase						,							_lowerCAmelCase								=ImageProcessingMixin.get_image_processor_dict(__UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
					if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
						_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

        # If not found, let's check whether the processor class is saved in a feature extractor config
				if preprocessor_config_file is not None and processor_class is None:
					_lowerCAmelCase						,							_lowerCAmelCase								=FeatureExtractionMixin.get_feature_extractor_dict(__UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
					if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
						_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

				if processor_class is None:
					# Next, let's check whether the processor class is saved in a tokenizer
					_lowerCAmelCase								=get_file_from_repo(
					    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
					if tokenizer_config_file is not None:
						with open(__UpperCAmelCase     ,     encoding="""utf-8"""  ) as reader:
							_lowerCAmelCase								=json.load(__UpperCAmelCase  )

						_lowerCAmelCase								=config_dict.get("""processor_class"""     ,     __UpperCAmelCase  )
						if "AutoProcessor" in config_dict.get("""auto_map"""     ,     {}  ):
							_lowerCAmelCase								=config_dict["""auto_map"""]["""AutoProcessor"""]

				if processor_class is None:
					# Otherwise, load config, if it can be loaded.
					if not isinstance(__UpperCAmelCase     ,     __UpperCAmelCase  ):
						_lowerCAmelCase								=AutoConfig.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )

					# And check if the config contains the processor class.
					_lowerCAmelCase								=getattr(__UpperCAmelCase     ,     """processor_class"""     ,     __UpperCAmelCase  )
					if hasattr(__UpperCAmelCase     ,     """auto_map"""  ) and "AutoProcessor" in config.auto_map:
						_lowerCAmelCase								=config.auto_map["""AutoProcessor"""]

				if processor_class is not None:
					_lowerCAmelCase								=processor_class_from_name(__UpperCAmelCase  )

				_lowerCAmelCase								=processor_auto_map is not None
				_lowerCAmelCase								=processor_class is not None or type(__UpperCAmelCase  ) in PROCESSOR_MAPPING
				_lowerCAmelCase								=resolve_trust_remote_code(
				    __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase  )

				if has_remote_code and trust_remote_code:
					_lowerCAmelCase								=get_class_from_dynamic_module(
					    __UpperCAmelCase     ,     __UpperCAmelCase     ,     **__UpperCAmelCase  )
					_lowerCAmelCase								=kwargs.pop("""code_revision"""     ,     __UpperCAmelCase  )
					if os.path.isdir(__UpperCAmelCase  ):
						processor_class.register_for_auto_class()
					return processor_class.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				elif processor_class is not None:
					return processor_class.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				# Last try: we use the PROCESSOR_MAPPING.
				elif type(__UpperCAmelCase  ) in PROCESSOR_MAPPING:
					return PROCESSOR_MAPPING[type(__UpperCAmelCase  )].from_pretrained(__UpperCAmelCase     ,     **__UpperCAmelCase  )

				# At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
				# tokenizer.
				try:
					return AutoTokenizer.from_pretrained(
					    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
				except Exception:
					try:
						return AutoImageProcessor.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
					except Exception:
						pass

					try:
						return AutoFeatureExtractor.from_pretrained(
						    __UpperCAmelCase     ,     trust_remote_code=__UpperCAmelCase     ,     **__UpperCAmelCase  )
					except Exception:
						pass

				raise ValueError(
				    f'''Unrecognized processing class in {pretrained_model_name_or_path}. Can\'t instantiate a processor, a '''
				    """tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains"""
				    """the files of at least one of those processing classes."""  )



			@staticmethod
			def 					_lowerCAmelCase		(							__UpperCAmelCase     ,     __UpperCAmelCase  ) ->     Optional[int]:
				PROCESSOR_MAPPING.register(__UpperCAmelCase     ,     __UpperCAmelCase  )



