




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,
)


UpperCAmelCase_		:				Optional[int]									=     logging.get_logger(__name__)

UpperCAmelCase_		:				List[str]									=     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"),
    ]
)

UpperCAmelCase_		:				List[str]									=     _LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)




def 		lowerCAmelCase_   (	lowerCamelCase   ):
				for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
								if class_name in extractors:
												__magic_name__	:	Union[str, Any]								=model_type_to_module_name(lowerCamelCase   )

												__magic_name__	:	Optional[Any]								=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.
				__magic_name__	:	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	,     ):
				__magic_name__	:	List[Any]								=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 		__A      :

						def __init__(		self   :List[Any] ):
										'''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(__snake_case )
						def     A__						(		cls   :Dict    , __snake_case   :Optional[int]    , **__snake_case   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	Tuple								=kwargs.pop("""config"""    , __snake_case )
										__magic_name__	:	List[str]								=kwargs.pop("""trust_remote_code"""    , __snake_case )
										__magic_name__	:	Optional[Any]								=True

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

										if feature_extractor_class is not None:
														__magic_name__	:	Optional[Any]								=feature_extractor_class_from_name(__snake_case )

										__magic_name__	:	str								=feature_extractor_auto_map is not None
										__magic_name__	:	Tuple								=feature_extractor_class is not None or type(__snake_case ) in FEATURE_EXTRACTOR_MAPPING
										__magic_name__	:	Optional[Any]								=resolve_trust_remote_code(
										    __snake_case    , __snake_case    , __snake_case    , __snake_case )

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

										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     A__						(		__snake_case   :str    , __snake_case   :str ):
										'''simple docstring'''

										FEATURE_EXTRACTOR_MAPPING.register(__snake_case    , __snake_case )










from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxSeqaSeqConfigWithPast
from ...utils import logging


UpperCAmelCase_		:				str									=     logging.get_logger(__name__)

UpperCAmelCase_		:				Tuple									=     {
    "t5-small": "https://huggingface.co/t5-small/resolve/main/config.json",
    "t5-base": "https://huggingface.co/t5-base/resolve/main/config.json",
    "t5-large": "https://huggingface.co/t5-large/resolve/main/config.json",
    "t5-3b": "https://huggingface.co/t5-3b/resolve/main/config.json",
    "t5-11b": "https://huggingface.co/t5-11b/resolve/main/config.json",
}




class 		__A      (			UpperCamelCase__			):
						UpperCamelCase     						=					"""t5"""
						UpperCamelCase     						=					["""past_key_values"""]
						UpperCamelCase     						=					{"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""}

						def __init__(		self   :Optional[Any]    , __snake_case   :Optional[Any]=3_21_28    , __snake_case   :Optional[int]=5_12    , __snake_case   :str=64    , __snake_case   :int=20_48    , __snake_case   :Union[str, Any]=6    , __snake_case   :Union[str, Any]=None    , __snake_case   :Union[str, Any]=8    , __snake_case   :List[str]=32    , __snake_case   :Dict=1_28    , __snake_case   :List[Any]=0.1    , __snake_case   :int=1E-6    , __snake_case   :List[str]=1.0    , __snake_case   :Optional[int]="relu"    , __snake_case   :List[str]=True    , __snake_case   :Union[str, Any]=True    , __snake_case   :Union[str, Any]=0    , __snake_case   :str=1    , **__snake_case   :int    , ):
										'''simple docstring'''

										__magic_name__	:	str								=vocab_size
										__magic_name__	:	str								=d_model
										__magic_name__	:	Optional[Any]								=d_kv
										__magic_name__	:	int								=d_ff
										__magic_name__	:	Union[str, Any]								=num_layers
										__magic_name__	:	Tuple								=(
										    num_decoder_layers if num_decoder_layers is not None else self.num_layers
										)  # default = symmetry
										__magic_name__	:	List[str]								=num_heads
										__magic_name__	:	Optional[Any]								=relative_attention_num_buckets
										__magic_name__	:	Union[str, Any]								=relative_attention_max_distance
										__magic_name__	:	Dict								=dropout_rate
										__magic_name__	:	Dict								=layer_norm_epsilon
										__magic_name__	:	List[str]								=initializer_factor
										__magic_name__	:	Any								=feed_forward_proj
										__magic_name__	:	Optional[int]								=use_cache

										__magic_name__	:	Tuple								=self.feed_forward_proj.split("""-""" )
										__magic_name__	:	int								=act_info[-1]
										__magic_name__	:	int								=act_info[0] == """gated"""

										if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2:
														raise ValueError(
														    f"`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer."
														    """Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. """
														    """'gated-gelu' or 'relu'""" )

										# for backwards compatibility
										if feed_forward_proj == "gated-gelu":
														__magic_name__	:	str								="""gelu_new"""

										super().__init__(
										    pad_token_id=__snake_case    , eos_token_id=__snake_case    , is_encoder_decoder=__snake_case    , **__snake_case    , )




class 		__A      (			UpperCamelCase__			):

						@property
						def     A__						(		self   :List[Any] ):
										'''simple docstring'''

										__magic_name__	:	int								={
										    """input_ids""": {0: """batch""", 1: """encoder_sequence"""},
										    """attention_mask""": {0: """batch""", 1: """encoder_sequence"""},
										}
										if self.use_past:
														__magic_name__	:	List[str]								="""past_encoder_sequence + sequence"""
														__magic_name__	:	List[Any]								={0: """batch"""}
														__magic_name__	:	Union[str, Any]								={0: """batch""", 1: """past_decoder_sequence + sequence"""}
										else:
														__magic_name__	:	int								={0: """batch""", 1: """decoder_sequence"""}
														__magic_name__	:	Tuple								={0: """batch""", 1: """decoder_sequence"""}

										if self.use_past:
														self.fill_with_past_key_values_(__snake_case    , direction="""inputs""" )

										return common_inputs


						@property
						def     A__						(		self   :Union[str, Any] ):
										'''simple docstring'''

										return 13




