
"""simple docstring"""


import inspect
import unittest
import warnings
from math import ceil, floor

from transformers import LevitConfig
from transformers.file_utils import cached_property, is_torch_available, is_vision_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_vision, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch

		from transformers import (
		    MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING,
		    MODEL_MAPPING,
		    LevitForImageClassification,
		    LevitForImageClassificationWithTeacher,
		    LevitModel,
		)
		from transformers.models.levit.modeling_levit import LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import LevitImageProcessor







class 					lowerCAmelCase_					(   a_     ):



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> List[str]:
							A     = self.config_class(**self.inputs_dict   )
							self.parent.assertTrue(hasattr(_lowercase	,'hidden_sizes'   )   )
							self.parent.assertTrue(hasattr(_lowercase	,'num_attention_heads'   )   )







class 					lowerCAmelCase_					:



						'''simple docstring'''


						def __init__(			self  :   Any	,A_  :   Tuple	,A_  :   Union[str, Any]=13	,A_  :   Any=64	,A_  :   Tuple=3	,A_  :   Dict=3	,A_  :   str=2	,A_  :   Tuple=1	,A_  :   Union[str, Any]=16	,A_  :   Optional[int]=[128, 256, 384]	,A_  :   int=[4, 6, 8]	,A_  :   List[str]=[2, 3, 4]	,A_  :   Union[str, Any]=[16, 16, 16]	,A_  :   Union[str, Any]=0	,A_  :   Optional[Any]=[2, 2, 2]	,A_  :   Any=[2, 2, 2]	,A_  :   str=0.02	,A_  :   Any=True	,A_  :   List[Any]=True	,A_  :   Optional[int]=2	,)  -> Optional[int]:
							A     = parent
							A     = batch_size
							A     = image_size
							A     = num_channels
							A     = kernel_size
							A     = stride
							A     = padding
							A     = hidden_sizes
							A     = num_attention_heads
							A     = depths
							A     = key_dim
							A     = drop_path_rate
							A     = patch_size
							A     = attention_ratio
							A     = mlp_ratio
							A     = initializer_range
							A     = [
							    ["""Subsample""", key_dim[0], hidden_sizes[0] // key_dim[0], 4, 2, 2],
							    ["""Subsample""", key_dim[0], hidden_sizes[1] // key_dim[0], 4, 2, 2],
							]
							A     = is_training
							A     = use_labels
							A     = num_labels
							A     = initializer_range


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[str]   )  -> str:
							A     = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

							A     = None
							if self.use_labels:
								A     = ids_tensor([self.batch_size]	,self.num_labels   )

							A     = self.get_config()
							return config, pixel_values, labels


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> int:
							return LevitConfig(
							    image_size=self.image_size	,num_channels=self.num_channels	,kernel_size=self.kernel_size	,stride=self.stride	,padding=self.padding	,patch_size=self.patch_size	,hidden_sizes=self.hidden_sizes	,num_attention_heads=self.num_attention_heads	,depths=self.depths	,key_dim=self.key_dim	,drop_path_rate=self.drop_path_rate	,mlp_ratio=self.mlp_ratio	,attention_ratio=self.attention_ratio	,initializer_range=self.initializer_range	,down_ops=self.down_ops	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]	,A_  :   Tuple	,A_  :   List[str]	,A_  :   Union[str, Any]   )  -> Dict:
							A     = LevitModel(config=_lowercase   )
							model.to(_lowercase   )
							model.eval()
							A     = model(_lowercase   )
							A     = (self.image_size, self.image_size)
							A     = image_size[0], image_size[1]
							for _ in range(4   ):
								A     = floor(((height + 2 * self.padding - self.kernel_size) / self.stride) + 1   )
								A     = floor(((width + 2 * self.padding - self.kernel_size) / self.stride) + 1   )
							self.parent.assertEqual(
							    result.last_hidden_state.shape	,(self.batch_size, ceil(height / 4   ) * ceil(width / 4   ), self.hidden_sizes[-1])	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]	,A_  :   Union[str, Any]	,A_  :   Tuple	,A_  :   str   )  -> Any:
							A     = self.num_labels
							A     = LevitForImageClassification(_lowercase   )
							model.to(_lowercase   )
							model.eval()
							A     = model(_lowercase	,labels=_lowercase   )
							self.parent.assertEqual(result.logits.shape	,(self.batch_size, self.num_labels)   )




						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> Tuple:
							A     = self.prepare_config_and_inputs()
							A     = config_and_inputs
							A     = {"""pixel_values""": pixel_values}
							return config, inputs_dict







@require_torch
class 					lowerCAmelCase_					(   a_		,       a_		,       unittest.TestCase     ):



						'''simple docstring'''


						_lowerCamelCase:     Union[str, Any]   =     (
						    (LevitModel, LevitForImageClassification, LevitForImageClassificationWithTeacher)
						    if is_torch_available()
						    else ()
						)
						_lowerCamelCase:     Tuple   =     (
						    {
						        '''feature-extraction''': LevitModel,
						        '''image-classification''': (LevitForImageClassification, LevitForImageClassificationWithTeacher),
						    }
						    if is_torch_available()
						    else {}
						)

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


						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> int:
							A     = LevitModelTester(self   )
							A     = ConfigTester(self	,config_class=_lowercase	,has_text_modality=_lowercase	,hidden_size=37   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> Union[str, Any]:
							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     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> List[str]:
							return


						@unittest.skip(reason='Levit does not use inputs_embeds'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Dict:
							pass


						@unittest.skip(reason='Levit does not support input and output embeddings'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> int:
							pass


						@unittest.skip(reason='Levit does not output attentions'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> Any:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Union[str, Any]:
							A     = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A     = model_class(_lowercase   )
								A     = inspect.signature(model.forward   )
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								A     = [*signature.parameters.keys()]

								A     = ["""pixel_values"""]
								self.assertListEqual(arg_names[:1]	,_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> Tuple:
							def check_hidden_states_output(A_  :   Union[str, Any]	,A_  :   Optional[Any]	,A_  :   Union[str, Any]   ):
								A     = model_class(_lowercase   )
								model.to(_lowercase   )
								model.eval()

								with torch.no_grad():
									A     = model(**self._prepare_for_class(_lowercase	,_lowercase   )   )

								A     = outputs.hidden_states

								A     = len(self.model_tester.depths   ) + 1
								self.assertEqual(len(_lowercase   )	,_lowercase   )

								A     = (self.model_tester.image_size, self.model_tester.image_size)
								A     = image_size[0], image_size[1]
								for _ in range(4   ):
									A     = floor(
									    (
									        (height + 2 * self.model_tester.padding - self.model_tester.kernel_size)
									        / self.model_tester.stride
									    )
									    + 1   )
									A     = floor(
									    (
									        (width + 2 * self.model_tester.padding - self.model_tester.kernel_size)
									        / self.model_tester.stride
									    )
									    + 1   )
								# verify the first hidden states (first block)
								self.assertListEqual(
								    list(hidden_states[0].shape[-2:]   )	,[
								        height * width,
								        self.model_tester.hidden_sizes[0],
								    ]	,)

							A     = self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
								A     = True
								check_hidden_states_output(_lowercase	,_lowercase	,_lowercase   )

								# check that output_hidden_states also work using config
								del inputs_dict["output_hidden_states"]
								A     = True

								check_hidden_states_output(_lowercase	,_lowercase	,_lowercase   )


						@unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'   )
						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> Tuple:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict	,A_  :   int	,A_  :   str	,A_  :   Tuple=False   )  -> Optional[Any]:
							A     = super()._prepare_for_class(_lowercase	,_lowercase	,return_labels=_lowercase   )

							if return_labels:
								if model_class.__name__ == "LevitForImageClassificationWithTeacher":
									del inputs_dict["labels"]

							return inputs_dict


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> List[Any]:
							A     = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> int:
							A     = self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> Optional[Any]:
							if not self.model_tester.is_training:
								return

							A     = self.model_tester.prepare_config_and_inputs_for_common()
							A     = True

							for model_class in self.all_model_classes:
								# LevitForImageClassificationWithTeacher supports inference-only
								if (
								    model_class in get_values(_lowercase   )
								    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
								):
									continue
								A     = model_class(_lowercase   )
								model.to(_lowercase   )
								model.train()
								A     = self._prepare_for_class(_lowercase	,_lowercase	,return_labels=_lowercase   )
								A     = model(**_lowercase   ).loss
								loss.backward()


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[str]   )  -> int:
							A     = self.model_tester.prepare_config_and_inputs_for_common()
							if not self.model_tester.is_training:
								return

							A     = False
							A     = True

							for model_class in self.all_model_classes:
								if model_class in get_values(_lowercase   ) or not model_class.supports_gradient_checkpointing:
									continue
								# LevitForImageClassificationWithTeacher supports inference-only
								if model_class.__name__ == "LevitForImageClassificationWithTeacher":
									continue
								A     = model_class(_lowercase   )
								model.gradient_checkpointing_enable()
								model.to(_lowercase   )
								model.train()
								A     = self._prepare_for_class(_lowercase	,_lowercase	,return_labels=_lowercase   )
								A     = model(**_lowercase   ).loss
								loss.backward()


						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> int:
							A     = self.model_tester.prepare_config_and_inputs_for_common()

							A     = [
							    {"""title""": """multi_label_classification""", """num_labels""": 2, """dtype""": torch.float},
							    {"""title""": """single_label_classification""", """num_labels""": 1, """dtype""": torch.long},
							    {"""title""": """regression""", """num_labels""": 1, """dtype""": torch.float},
							]

							for model_class in self.all_model_classes:
								if (
								    model_class
								    not in [
								        *get_values(_lowercase   ),
								    ]
								    or model_class.__name__ == "LevitForImageClassificationWithTeacher"
								):
									continue

								for problem_type in problem_types:
									with self.subTest(msg=F'Testing {model_class} with {problem_type["title"]}'   ):
										A     = problem_type["""title"""]
										A     = problem_type["""num_labels"""]

										A     = model_class(_lowercase   )
										model.to(_lowercase   )
										model.train()

										A     = self._prepare_for_class(_lowercase	,_lowercase	,return_labels=_lowercase   )

										if problem_type["num_labels"] > 1:
											A     = inputs["""labels"""].unsqueeze(1   ).repeat(1	,problem_type['num_labels']   )

										A     = inputs["""labels"""].to(problem_type['dtype']   )

										# This tests that we do not trigger the warning form PyTorch "Using a target size that is different
										# to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
										# they have the same size." which is a symptom something in wrong for the regression problem.
										# See https://github.com/huggingface/transformers/issues/11780
										with warnings.catch_warnings(record=_lowercase   ) as warning_list:
											A     = model(**_lowercase   ).loss
										for w in warning_list:
											if "Using a target size that is different to the input size" in str(w.message   ):
												raise ValueError(
												    F'Something is going wrong in the regression problem: intercepted {w.message}'   )

										loss.backward()




						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> List[Any]:
							for model_name in LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								A     = LevitModel.from_pretrained(_lowercase   )
								self.assertIsNotNone(_lowercase   )






def    _snake_case					(		):
	A     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
	return image







@require_torch
@require_vision
class 					lowerCAmelCase_					(   unittest.TestCase     ):



						'''simple docstring'''


						@cached_property
						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> Any:
							return LevitImageProcessor.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   )




						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]   )  -> Union[str, Any]:
							A     = LevitForImageClassificationWithTeacher.from_pretrained(LEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]   ).to(
							    _lowercase   )

							A     = self.default_image_processor
							A     = prepare_img()
							A     = image_processor(images=_lowercase	,return_tensors='pt'   ).to(_lowercase   )

							# forward pass
							with torch.no_grad():
								A     = model(**_lowercase   )

							# verify the logits
							A     = torch.Size((1, 1000)   )
							self.assertEqual(outputs.logits.shape	,_lowercase   )

							A     = torch.tensor([1.04_48, -0.37_45, -1.83_17]   ).to(_lowercase   )

							self.assertTrue(torch.allclose(outputs.logits[0, :3]	,_lowercase	,atol=1e-4   )   )


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


__snake_case				:      Union[str, Any]   		=			logging.get_logger(__name__)

__snake_case				:      Tuple   		=			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"""),
    ]
)

__snake_case				:      List[Any]   		=			_LazyAutoMapping(CONFIG_MAPPING_NAMES, FEATURE_EXTRACTOR_MAPPING_NAMES)


def 					_UpperCAmelCase				(						a__):

			'''simple docstring'''



			for module_name, extractors in FEATURE_EXTRACTOR_MAPPING_NAMES.items():
						if class_name in extractors:
									a_						:						Tuple 							= model_type_to_module_name(a__)

									a_						:						Any 							= 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.
			a_						:						Tuple 							= importlib.import_module("""transformers""")
			if hasattr(a__  ,	a__):
						return getattr(a__  ,	a__)

			return None


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

			'''simple docstring'''



			a_						:						List[str] 							= 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        A__:
						"""simple docstring"""






						def __init__(    self    )     -> List[str]:
									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(_lowercase    )
						def 			UpperCamelCase__					(    cls  ,      _lowercase  ,      **_lowercase    )     -> Dict:
									a_						:						Tuple 							= kwargs.pop("""config"""  ,      _lowercase    )
									a_						:						Dict 							= kwargs.pop("""trust_remote_code"""  ,      _lowercase    )
									a_						:						Dict 							= True

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

									if feature_extractor_class is not None:
												a_						:						int 							= feature_extractor_class_from_name(_lowercase    )

									a_						:						Dict 							= feature_extractor_auto_map is not None
									a_						:						Union[str, Any] 							= feature_extractor_class is not None or type(_lowercase    ) in FEATURE_EXTRACTOR_MAPPING
									a_						:						Optional[Any] 							= resolve_trust_remote_code(
									    _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase    )

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

									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 			UpperCamelCase__					(    _lowercase  ,      _lowercase    )     -> List[Any]:
									FEATURE_EXTRACTOR_MAPPING.register(_lowercase  ,      _lowercase    )


