
"""simple docstring"""


from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
		from transformers import (
		    TFBertModel,
		    TFCLIPVisionModel,
		    TFDeiTModel,
		    TFRobertaModel,
		    TFVisionTextDualEncoderModel,
		    TFViTModel,
		    VisionTextDualEncoderConfig,
		)

if is_vision_available():
		from PIL import Image

		from transformers import VisionTextDualEncoderProcessor






def    _snake_case					(		snake_case__ :  List[Any]  ):



	if isinstance(a__						,   collections.abc.Iterable  ):
		return x
	return (x, x)







@require_tf
class 					lowerCAmelCase_					:



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]	,A_  :   str	,A_  :   Optional[int]   )  -> Dict:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> Any:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]   )  -> List[str]:
							pass


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]	,A_  :   List[str]	,A_  :   Dict	,A_  :   Optional[int]	,A_  :   int	,A_  :   List[Any]=None	,**A_  :   List[Any]   )  -> List[str]:
							A     = VisionTextDualEncoderConfig.from_vision_text_configs(_lowercase	,_lowercase   )

							A     = TFVisionTextDualEncoderModel(_lowercase   )

							A     = model(input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase   )

							self.assertEqual(output['text_embeds'].shape	,(input_ids.shape[0], config.projection_dim)   )
							self.assertEqual(output['image_embeds'].shape	,(pixel_values.shape[0], config.projection_dim)   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict	,A_  :   str	,A_  :   Optional[int]	,A_  :   List[str]	,A_  :   List[Any]	,A_  :   List[Any]=None	,**A_  :   Dict   )  -> Optional[Any]:
							A     = self.get_vision_text_model(_lowercase	,_lowercase   )
							A     = TFVisionTextDualEncoderModel(vision_model=_lowercase	,text_model=_lowercase   )

							A     = model(input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase   )

							self.assertEqual(output['text_embeds'].shape	,(input_ids.shape[0], model.config.projection_dim)   )
							self.assertEqual(output['image_embeds'].shape	,(pixel_values.shape[0], model.config.projection_dim)   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple	,A_  :   str	,A_  :   List[Any]	,A_  :   Dict	,A_  :   Optional[Any]	,A_  :   Optional[int]=None	,**A_  :   Dict   )  -> Optional[int]:
							A     = self.get_vision_text_model(_lowercase	,_lowercase   )
							A     = {"""vision_model""": vision_model, """text_model""": text_model}
							A     = TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowercase   )

							A     = model(input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase   )

							self.assertEqual(output['text_embeds'].shape	,(input_ids.shape[0], model.config.projection_dim)   )
							self.assertEqual(output['image_embeds'].shape	,(pixel_values.shape[0], model.config.projection_dim)   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict	,A_  :   int	,A_  :   Optional[Any]	,A_  :   Dict	,A_  :   Optional[int]	,A_  :   str=None	,**A_  :   str   )  -> str:
							A     = self.get_vision_text_model(_lowercase	,_lowercase   )
							A     = TFVisionTextDualEncoderModel(vision_model=_lowercase	,text_model=_lowercase   )

							A     = model(input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase   )
							A     = output[0].numpy()

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(_lowercase   )
								A     = TFVisionTextDualEncoderModel.from_pretrained(_lowercase   )

								A     = model(input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase   )
								A     = after_output[0].numpy()
								A     = np.amax(np.abs(out_a - out_a   )   )
								self.assertLessEqual(_lowercase	,1e-5   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]	,A_  :   List[Any]	,A_  :   Any	,A_  :   str	,A_  :   str	,A_  :   Dict=None	,**A_  :   List[str]   )  -> List[Any]:
							A     = self.get_vision_text_model(_lowercase	,_lowercase   )
							A     = TFVisionTextDualEncoderModel(vision_model=_lowercase	,text_model=_lowercase   )

							A     = model(
							    input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase	,output_attentions=_lowercase   )

							A     = output.vision_model_output.attentions
							self.assertEqual(len(_lowercase   )	,vision_config.num_hidden_layers   )

							# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
							A     = to_atuple(vision_model.config.image_size   )
							A     = to_atuple(vision_model.config.patch_size   )
							A     = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
							A     = num_patches + 1
							self.assertEqual(vision_attentions[0].shape[-3:]	,(vision_config.num_attention_heads, seq_len, seq_len)   )

							A     = output.text_model_output.attentions
							self.assertEqual(len(_lowercase   )	,text_config.num_hidden_layers   )

							self.assertEqual(
							    text_attentions[0].shape[-3:]	,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   str	,A_  :   Union[str, Any]	,A_  :   Dict	,A_  :   Tuple   )  -> Optional[int]:
							A     = np.abs((a - b)   ).max()
							self.assertLessEqual(_lowercase	,_lowercase	,F'Difference between torch and flax is {diff} (>= {tol}).'   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]   )  -> Union[str, Any]:
							A     = self.prepare_config_and_inputs()
							self.check_vision_text_dual_encoder_model(**_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   str   )  -> Optional[int]:
							A     = self.prepare_config_and_inputs()
							self.check_model_from_pretrained_configs(**_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Any:
							A     = self.prepare_config_and_inputs()
							self.check_vision_text_dual_encoder_from_pretrained(**_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> str:
							A     = self.prepare_config_and_inputs()
							self.check_save_load(**_lowercase   )


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> Union[str, Any]:
							A     = self.prepare_config_and_inputs()
							self.check_vision_text_output_attention(**_lowercase   )




						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   Any   )  -> Tuple:
							A     = self.get_pretrained_model_and_inputs()

							A     = model_a(**_lowercase   )
							A     = outputs[0].numpy()

							with tempfile.TemporaryDirectory() as tmp_dirname:
								model_a.save_pretrained(_lowercase   )
								A     = TFVisionTextDualEncoderModel.from_pretrained(_lowercase   )

								A     = model_a(**_lowercase   )
								A     = after_outputs[0].numpy()
								A     = np.amax(np.abs(out_a - out_a   )   )
								self.assertLessEqual(_lowercase	,1e-5   )







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



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> List[str]:
							A     = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
							    'hf-internal-testing/tiny-random-vit'	,'hf-internal-testing/tiny-random-bert'   )
							A     = 13
							A     = floats_tensor(
							    [
							        batch_size,
							        model.vision_model.config.num_channels,
							        model.vision_model.config.image_size,
							        model.vision_model.config.image_size,
							    ]   )
							A     = ids_tensor([batch_size, 4]	,model.text_model.config.vocab_size   )
							A     = random_attention_mask([batch_size, 4]   )
							A     = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

							return model, inputs


						def     _SCREAMING_SNAKE_CASE   (			self  :   str	,A_  :   Tuple	,A_  :   Tuple   )  -> Dict:
							A     = TFViTModel(_lowercase	,name='vision_model'   )
							A     = TFBertModel(_lowercase	,name='text_model'   )
							return vision_model, text_model




						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]   )  -> Tuple:
							A     = TFViTModelTester(self   )
							A     = TFBertModelTester(self   )
							A     = vit_model_tester.prepare_config_and_inputs()
							A     = bert_model_tester.prepare_config_and_inputs()

							A     = vision_config_and_inputs

							(
							    A					
							)     = text_config_and_inputs

							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": input_mask,
							    "input_ids": input_ids,
							    "text_token_type_ids": token_type_ids,
							    "text_sequence_labels": sequence_labels,
							    "text_token_labels": token_labels,
							    "text_choice_labels": choice_labels,
							}







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



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   Dict   )  -> List[str]:
							# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
							# just reinitialize it.
							A     = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
							    'Rocketknight1/tiny-random-deit-tf'	,'hf-internal-testing/tiny-random-roberta'   )
							A     = 13
							A     = floats_tensor(
							    [
							        batch_size,
							        model.vision_model.config.num_channels,
							        model.vision_model.config.image_size,
							        model.vision_model.config.image_size,
							    ]   )
							A     = ids_tensor([batch_size, 4]	,model.text_model.config.vocab_size   )
							A     = random_attention_mask([batch_size, 4]   )
							A     = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

							return model, inputs


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[int]	,A_  :   Dict	,A_  :   Union[str, Any]	,A_  :   Optional[int]	,A_  :   Union[str, Any]	,A_  :   int=None	,**A_  :   Optional[Any]   )  -> List[Any]:
							A     = self.get_vision_text_model(_lowercase	,_lowercase   )
							A     = TFVisionTextDualEncoderModel(vision_model=_lowercase	,text_model=_lowercase   )

							A     = model(
							    input_ids=_lowercase	,pixel_values=_lowercase	,attention_mask=_lowercase	,output_attentions=_lowercase   )

							A     = output.vision_model_output.attentions
							self.assertEqual(len(_lowercase   )	,vision_config.num_hidden_layers   )

							# in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
							A     = to_atuple(vision_model.config.image_size   )
							A     = to_atuple(vision_model.config.patch_size   )
							A     = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
							A     = num_patches + 2
							self.assertEqual(vision_attentions[0].shape[-3:]	,(vision_config.num_attention_heads, seq_len, seq_len)   )

							A     = output.text_model_output.attentions
							self.assertEqual(len(_lowercase   )	,text_config.num_hidden_layers   )

							self.assertEqual(
							    text_attentions[0].shape[-3:]	,(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])	,)


						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]	,A_  :   Dict	,A_  :   Optional[int]   )  -> Dict:
							A     = TFDeiTModel(_lowercase	,name='vision_model'   )
							A     = TFRobertaModel(_lowercase	,name='text_model'   )
							return vision_model, text_model




						def     _SCREAMING_SNAKE_CASE   (			self  :   Union[str, Any]   )  -> Optional[Any]:
							A     = TFDeiTModelTester(self   )
							A     = TFRobertaModelTester(self   )
							A     = vit_model_tester.prepare_config_and_inputs()
							A     = bert_model_tester.prepare_config_and_inputs()

							A     = vision_config_and_inputs

							(
							    A					
							)     = text_config_and_inputs

							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": input_mask,
							    "input_ids": input_ids,
							    "text_token_type_ids": token_type_ids,
							    "text_sequence_labels": sequence_labels,
							    "text_token_labels": token_labels,
							    "text_choice_labels": choice_labels,
							}







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



						'''simple docstring'''


						def     _SCREAMING_SNAKE_CASE   (			self  :   List[Any]   )  -> List[str]:
							A     = TFVisionTextDualEncoderModel.from_vision_text_pretrained(
							    'Rocketknight1/tiny-random-clip-tf'	,'hf-internal-testing/tiny-random-bert'   )
							A     = 13
							A     = floats_tensor(
							    [
							        batch_size,
							        model.vision_model.config.num_channels,
							        model.vision_model.config.image_size,
							        model.vision_model.config.image_size,
							    ]   )
							A     = ids_tensor([batch_size, 4]	,model.text_model.config.vocab_size   )
							A     = random_attention_mask([batch_size, 4]   )
							A     = {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

							return model, inputs


						def     _SCREAMING_SNAKE_CASE   (			self  :   Optional[Any]	,A_  :   int	,A_  :   Tuple   )  -> Union[str, Any]:
							A     = TFCLIPVisionModel(_lowercase	,name='vision_model'   )
							A     = TFBertModel(_lowercase	,name='text_model'   )
							return vision_model, text_model




						def     _SCREAMING_SNAKE_CASE   (			self  :   Tuple   )  -> Optional[Any]:
							A     = TFCLIPVisionModelTester(self   )
							A     = TFBertModelTester(self   )
							A     = clip_model_tester.prepare_config_and_inputs()
							A     = bert_model_tester.prepare_config_and_inputs()

							A     = vision_config_and_inputs

							(
							    A					
							)     = text_config_and_inputs

							return {
							    "text_config": text_config,
							    "vision_config": vision_config,
							    "pixel_values": pixel_values,
							    "attention_mask": input_mask,
							    "input_ids": input_ids,
							    "text_token_type_ids": token_type_ids,
							    "text_sequence_labels": sequence_labels,
							    "text_token_labels": token_labels,
							    "text_choice_labels": choice_labels,
							}







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



						'''simple docstring'''


						@slow
						def     _SCREAMING_SNAKE_CASE   (			self  :   int   )  -> List[Any]:
							A     = TFVisionTextDualEncoderModel.from_pretrained(
							    'clip-italian/clip-italian'	,logit_scale_init_value=1.0	,from_pt=_lowercase   )
							A     = VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'   )

							A     = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
							A     = processor(
							    text=['una foto di un gatto', 'una foto di un cane']	,images=_lowercase	,padding=_lowercase	,return_tensors='np'   )

							A     = model(**_lowercase   )

							# verify the logits
							self.assertEqual(outputs.logits_per_image.shape	,(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])   )
							self.assertEqual(
							    outputs.logits_per_text.shape	,(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])	,)

							A     = np.array([[1.2_28_47_27, 0.3_10_41_22]]   )

							self.assertTrue(np.allclose(outputs.logits_per_image.numpy()	,_lowercase	,atol=1e-3   )   )


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    )


