

import collections
import inspect
import unittest

from transformers import SwinvaConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
	import torch
	from torch import nn

	from transformers import SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
	from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
	from PIL import Image

	from transformers import AutoImageProcessor



class        A__:
						"""simple docstring"""






						def __init__(    self  ,      _lowercase  ,      _lowercase=13  ,      _lowercase=32  ,      _lowercase=2  ,      _lowercase=3  ,      _lowercase=16  ,      _lowercase=[1, 2, 1]  ,      _lowercase=[2, 2, 4]  ,      _lowercase=2  ,      _lowercase=2.0  ,      _lowercase=True  ,      _lowercase=0.0  ,      _lowercase=0.0  ,      _lowercase=0.1  ,      _lowercase="gelu"  ,      _lowercase=False  ,      _lowercase=True  ,      _lowercase=0.0_2  ,      _lowercase=1e-5  ,      _lowercase=True  ,      _lowercase=None  ,      _lowercase=True  ,      _lowercase=10  ,      _lowercase=8  ,      )     -> Union[str, Any]:
									a_						:						Optional[int] 							= parent
									a_						:						int 							= batch_size
									a_						:						List[Any] 							= image_size
									a_						:						Optional[int] 							= patch_size
									a_						:						Dict 							= num_channels
									a_						:						Any 							= embed_dim
									a_						:						Union[str, Any] 							= depths
									a_						:						str 							= num_heads
									a_						:						List[str] 							= window_size
									a_						:						Optional[Any] 							= mlp_ratio
									a_						:						Dict 							= qkv_bias
									a_						:						Optional[int] 							= hidden_dropout_prob
									a_						:						Any 							= attention_probs_dropout_prob
									a_						:						Optional[int] 							= drop_path_rate
									a_						:						Optional[Any] 							= hidden_act
									a_						:						Dict 							= use_absolute_embeddings
									a_						:						Optional[Any] 							= patch_norm
									a_						:						str 							= layer_norm_eps
									a_						:						Tuple 							= initializer_range
									a_						:						List[Any] 							= is_training
									a_						:						int 							= scope
									a_						:						Union[str, Any] 							= use_labels
									a_						:						str 							= type_sequence_label_size
									a_						:						List[str] 							= encoder_stride





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						Tuple 							= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

									a_						:						Optional[int] 							= None
									if self.use_labels:
												a_						:						Any 							= ids_tensor([self.batch_size]  ,      self.type_sequence_label_size    )

									a_						:						str 							= self.get_config()

									return config, pixel_values, labels





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									return SwinvaConfig(
									    image_size=self.image_size  ,      patch_size=self.patch_size  ,      num_channels=self.num_channels  ,      embed_dim=self.embed_dim  ,      depths=self.depths  ,      num_heads=self.num_heads  ,      window_size=self.window_size  ,      mlp_ratio=self.mlp_ratio  ,      qkv_bias=self.qkv_bias  ,      hidden_dropout_prob=self.hidden_dropout_prob  ,      attention_probs_dropout_prob=self.attention_probs_dropout_prob  ,      drop_path_rate=self.drop_path_rate  ,      hidden_act=self.hidden_act  ,      use_absolute_embeddings=self.use_absolute_embeddings  ,      path_norm=self.patch_norm  ,      layer_norm_eps=self.layer_norm_eps  ,      initializer_range=self.initializer_range  ,      encoder_stride=self.encoder_stride  ,      )





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase  ,      _lowercase    )     -> Any:
									a_						:						Optional[int] 							= SwinvaModel(config=_lowercase    )
									model.to(_lowercase    )
									model.eval()
									a_						:						Optional[int] 							= model(_lowercase    )

									a_						:						Optional[Any] 							= ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths    ) - 1))
									a_						:						Tuple 							= int(config.embed_dim * 2 ** (len(config.depths    ) - 1)    )

									self.parent.assertEqual(result.last_hidden_state.shape  ,      (self.batch_size, expected_seq_len, expected_dim)    )





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase  ,      _lowercase    )     -> int:
									a_						:						int 							= SwinvaForMaskedImageModeling(config=_lowercase    )
									model.to(_lowercase    )
									model.eval()
									a_						:						List[Any] 							= model(_lowercase    )
									self.parent.assertEqual(
									    result.logits.shape  ,      (self.batch_size, self.num_channels, self.image_size, self.image_size)    )

									# test greyscale images
									a_						:						Any 							= 1
									a_						:						Union[str, Any] 							= SwinvaForMaskedImageModeling(_lowercase    )
									model.to(_lowercase    )
									model.eval()

									a_						:						Optional[Any] 							= floats_tensor([self.batch_size, 1, self.image_size, self.image_size]    )
									a_						:						Optional[Any] 							= model(_lowercase    )
									self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, 1, self.image_size, self.image_size)    )





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase  ,      _lowercase    )     -> Optional[Any]:
									a_						:						Union[str, Any] 							= self.type_sequence_label_size
									a_						:						Dict 							= SwinvaForImageClassification(_lowercase    )
									model.to(_lowercase    )
									model.eval()
									a_						:						Dict 							= model(_lowercase  ,      labels=_lowercase    )
									self.parent.assertEqual(result.logits.shape  ,      (self.batch_size, self.type_sequence_label_size)    )





						def 			UpperCamelCase__					(    self    )     -> str:
									a_						:						List[Any] 							= self.prepare_config_and_inputs()
									a_							,					a_							,					a_						:						Optional[int] 							= config_and_inputs
									a_						:						Any 							= {"""pixel_values""": pixel_values}
									return config, inputs_dict







@require_torch
class        A__(a_,  a_,  unittest.TestCase							):
						"""simple docstring"""






						_A    :				Optional[Any]       					=			(
						    (SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
						)
						_A    :				Any       					=			(
						    {'''feature-extraction''': SwinvaModel, '''image-classification''': SwinvaForImageClassification}
						    if is_torch_available()
						    else {}
						)

						_A    :				Union[str, Any]       					=			False
						_A    :				Any       					=			False
						_A    :				int       					=			False
						_A    :				Tuple       					=			False





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_						:						Any 							= SwinvaModelTester(self    )
									a_						:						List[str] 							= ConfigTester(self  ,      config_class=_lowercase  ,      embed_dim=37    )





						def 			UpperCamelCase__					(    self    )     -> str:
									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 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									a_						:						int 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_lowercase    )





						@unittest.skip(reason="""Got `CUDA error: misaligned address` with PyTorch 2.0.0."""    )
						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									pass





						@unittest.skip(reason="""Swinv2 does not use inputs_embeds"""    )
						def 			UpperCamelCase__					(    self    )     -> int:
									pass





						def 			UpperCamelCase__					(    self    )     -> Dict:
									a_							,					a_						:						Tuple 							= self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												a_						:						str 							= model_class(_lowercase    )
												self.assertIsInstance(model.get_input_embeddings()  ,      (nn.Module)    )
												a_						:						Optional[int] 							= model.get_output_embeddings()
												self.assertTrue(x is None or isinstance(_lowercase  ,      nn.Linear    )    )





						def 			UpperCamelCase__					(    self    )     -> Any:
									a_							,					a_						:						Union[str, Any] 							= self.model_tester.prepare_config_and_inputs_for_common()

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

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





						def 			UpperCamelCase__					(    self    )     -> Tuple:
									a_							,					a_						:						Dict 							= self.model_tester.prepare_config_and_inputs_for_common()
									a_						:						Any 							= True

									for model_class in self.all_model_classes:
												a_						:						Tuple 							= True
												a_						:						Union[str, Any] 							= False
												a_						:						str 							= True
												a_						:						List[str] 							= model_class(_lowercase    )
												model.to(_lowercase    )
												model.eval()
												with torch.no_grad():
															a_						:						List[Any] 							= model(**self._prepare_for_class(_lowercase  ,      _lowercase    )    )
												a_						:						int 							= outputs.attentions
												a_						:						Tuple 							= len(self.model_tester.depths    )
												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

												# check that output_attentions also work using config
												del inputs_dict["output_attentions"]
												a_						:						Union[str, Any] 							= True
												a_						:						int 							= config.window_size**2
												a_						:						str 							= model_class(_lowercase    )
												model.to(_lowercase    )
												model.eval()
												with torch.no_grad():
															a_						:						str 							= model(**self._prepare_for_class(_lowercase  ,      _lowercase    )    )
												a_						:						Optional[int] 							= outputs.attentions
												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

												self.assertListEqual(
												    list(attentions[0].shape[-3:]    )  ,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]  ,      )
												a_						:						int 							= len(_lowercase    )

												# Check attention is always last and order is fine
												a_						:						Tuple 							= True
												a_						:						Optional[Any] 							= True
												a_						:						Optional[Any] 							= model_class(_lowercase    )
												model.to(_lowercase    )
												model.eval()
												with torch.no_grad():
															a_						:						str 							= model(**self._prepare_for_class(_lowercase  ,      _lowercase    )    )

												if hasattr(self.model_tester  ,      """num_hidden_states_types"""    ):
															a_						:						str 							= self.model_tester.num_hidden_states_types
												else:
															# also another +1 for reshaped_hidden_states
															a_						:						int 							= 2
												self.assertEqual(out_len + added_hidden_states  ,      len(_lowercase    )    )

												a_						:						str 							= outputs.attentions

												self.assertEqual(len(_lowercase    )  ,      _lowercase    )

												self.assertListEqual(
												    list(self_attentions[0].shape[-3:]    )  ,      [self.model_tester.num_heads[0], window_size_squared, window_size_squared]  ,      )





						def 			UpperCamelCase__					(    self  ,      _lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase    )     -> Dict:
									a_						:						List[Any] 							= model_class(_lowercase    )
									model.to(_lowercase    )
									model.eval()

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

									a_						:						Dict 							= outputs.hidden_states

									a_						:						Optional[int] 							= getattr(
									    self.model_tester  ,      """expected_num_hidden_layers"""  ,      len(self.model_tester.depths    ) + 1    )
									self.assertEqual(len(_lowercase    )  ,      _lowercase    )

									# Swinv2 has a different seq_length
									a_						:						Tuple 							= (
									    config.patch_size
									    if isinstance(config.patch_size  ,      collections.abc.Iterable    )
									    else (config.patch_size, config.patch_size)
									)

									a_						:						Optional[Any] 							= (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

									self.assertListEqual(
									    list(hidden_states[0].shape[-2:]    )  ,      [num_patches, self.model_tester.embed_dim]  ,      )

									a_						:						int 							= outputs.reshaped_hidden_states
									self.assertEqual(len(_lowercase    )  ,      _lowercase    )

									a_							,					a_							,					a_							,					a_						:						Tuple 							= reshaped_hidden_states[0].shape
									a_						:						Dict 							= (
									    reshaped_hidden_states[0].view(_lowercase  ,      _lowercase  ,      height * width    ).permute(0  ,      2  ,      1    )
									)
									self.assertListEqual(
									    list(reshaped_hidden_states.shape[-2:]    )  ,      [num_patches, self.model_tester.embed_dim]  ,      )





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_							,					a_						:						str 							= self.model_tester.prepare_config_and_inputs_for_common()

									a_						:						Any 							= (
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size  ,      collections.abc.Iterable    )
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)

									for model_class in self.all_model_classes:
												a_						:						Optional[int] 							= True
												self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase    )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												a_						:						str 							= True

												self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      _lowercase    )





						def 			UpperCamelCase__					(    self    )     -> List[str]:
									a_							,					a_						:						Tuple 							= self.model_tester.prepare_config_and_inputs_for_common()
									a_						:						Dict 							= 3

									a_						:						str 							= (
									    self.model_tester.image_size
									    if isinstance(self.model_tester.image_size  ,      collections.abc.Iterable    )
									    else (self.model_tester.image_size, self.model_tester.image_size)
									)
									a_						:						Dict 							= (
									    config.patch_size
									    if isinstance(config.patch_size  ,      collections.abc.Iterable    )
									    else (config.patch_size, config.patch_size)
									)

									a_						:						Tuple 							= image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
									a_						:						List[str] 							= image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

									for model_class in self.all_model_classes:
												a_						:						int 							= True
												self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      (padded_height, padded_width)    )

												# check that output_hidden_states also work using config
												del inputs_dict["output_hidden_states"]
												a_						:						Any 							= True
												self.check_hidden_states_output(_lowercase  ,      _lowercase  ,      _lowercase  ,      (padded_height, padded_width)    )





						def 			UpperCamelCase__					(    self    )     -> Optional[int]:
									a_						:						Optional[int] 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									a_						:						Optional[Any] 							= self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*_lowercase    )





						@slow
						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												a_						:						Any 							= SwinvaModel.from_pretrained(_lowercase    )
												self.assertIsNotNone(_lowercase    )





						def 			UpperCamelCase__					(    self    )     -> Optional[Any]:
									a_							,					a_						:						Optional[Any] 							= self.model_tester.prepare_config_and_inputs_for_common()

									a_						:						int 							= _config_zero_init(_lowercase    )
									for model_class in self.all_model_classes:
												a_						:						Dict 							= model_class(config=_lowercase    )
												for name, param in model.named_parameters():
															if "embeddings" not in name and "logit_scale" not in name and param.requires_grad:
																		self.assertIn(
																		    ((param.data.mean() * 1e9).round() / 1e9).item()  ,      [0.0, 1.0]  ,      msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''  ,      )







@require_vision
@require_torch
class        A__(unittest.TestCase							):
						"""simple docstring"""






						@cached_property
						def 			UpperCamelCase__					(    self    )     -> Dict:
									return (
									    AutoImageProcessor.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""    )
									    if is_vision_available()
									    else None
									)





						@slow
						def 			UpperCamelCase__					(    self    )     -> Union[str, Any]:
									a_						:						Optional[int] 							= SwinvaForImageClassification.from_pretrained("""microsoft/swinv2-tiny-patch4-window8-256"""    ).to(
									    _lowercase    )
									a_						:						str 							= self.default_image_processor

									a_						:						str 							= Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""    )
									a_						:						int 							= image_processor(images=_lowercase  ,      return_tensors="""pt"""    ).to(_lowercase    )

									# forward pass
									with torch.no_grad():
												a_						:						List[Any] 							= model(**_lowercase    )

									# verify the logits
									a_						:						Tuple 							= torch.Size((1, 1_000)    )
									self.assertEqual(outputs.logits.shape  ,      _lowercase    )
									a_						:						str 							= torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6]    ).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    )


