

import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


lowerCAmelCase							:  Tuple   	=						logging.get_logger(__name__)

lowerCAmelCase							:  List[Any]   	=						{
    """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""",
    # See all BART models at https://huggingface.co/models?filter=bart
}



class   __lowercase				( __lowerCamelCase	):




			"""simple docstring"""







			_UpperCAmelCase   :							Dict										=     'bart'
			_UpperCAmelCase   :							Dict										=     ['past_key_values']
			_UpperCAmelCase   :							Union[str, Any]										=     {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}



			def __init__( self  :     str   ,						lowerCAmelCase__  :     Any=5_0265   ,						lowerCAmelCase__  :     Dict=1024   ,						lowerCAmelCase__  :     Optional[int]=12   ,						lowerCAmelCase__  :     Dict=4096   ,						lowerCAmelCase__  :     List[str]=16   ,						lowerCAmelCase__  :     Union[str, Any]=12   ,						lowerCAmelCase__  :     Union[str, Any]=4096   ,						lowerCAmelCase__  :     List[Any]=16   ,						lowerCAmelCase__  :     Tuple=0.0   ,						lowerCAmelCase__  :     str=0.0   ,						lowerCAmelCase__  :     Any="gelu"   ,						lowerCAmelCase__  :     List[Any]=1024   ,						lowerCAmelCase__  :     Dict=0.1   ,						lowerCAmelCase__  :     List[str]=0.0   ,						lowerCAmelCase__  :     List[Any]=0.0   ,						lowerCAmelCase__  :     str=0.02   ,						lowerCAmelCase__  :     List[Any]=0.0   ,						lowerCAmelCase__  :     Dict=False   ,						lowerCAmelCase__  :     List[Any]=True   ,						lowerCAmelCase__  :     Dict=3   ,						lowerCAmelCase__  :     Optional[Any]=1   ,						lowerCAmelCase__  :     Dict=0   ,						lowerCAmelCase__  :     Optional[Any]=2   ,						lowerCAmelCase__  :     str=True   ,						lowerCAmelCase__  :     Union[str, Any]=2   ,						lowerCAmelCase__  :     List[Any]=2   ,						**lowerCAmelCase__  :     int   ,						):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       vocab_size
									SCREAMING_SNAKE_CASE_: List[Any]  		=       max_position_embeddings
									SCREAMING_SNAKE_CASE_: str  		=       d_model
									SCREAMING_SNAKE_CASE_: int  		=       encoder_ffn_dim
									SCREAMING_SNAKE_CASE_: int  		=       encoder_layers
									SCREAMING_SNAKE_CASE_: Dict  		=       encoder_attention_heads
									SCREAMING_SNAKE_CASE_: List[str]  		=       decoder_ffn_dim
									SCREAMING_SNAKE_CASE_: Tuple  		=       decoder_layers
									SCREAMING_SNAKE_CASE_: List[str]  		=       decoder_attention_heads
									SCREAMING_SNAKE_CASE_: str  		=       dropout
									SCREAMING_SNAKE_CASE_: List[Any]  		=       attention_dropout
									SCREAMING_SNAKE_CASE_: List[Any]  		=       activation_dropout
									SCREAMING_SNAKE_CASE_: int  		=       activation_function
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       init_std
									SCREAMING_SNAKE_CASE_: int  		=       encoder_layerdrop
									SCREAMING_SNAKE_CASE_: Any  		=       decoder_layerdrop
									SCREAMING_SNAKE_CASE_: List[Any]  		=       classifier_dropout
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       use_cache
									SCREAMING_SNAKE_CASE_: Tuple  		=       encoder_layers
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       scale_embedding  # scale factor will be sqrt(d_model) if True

									super().__init__(
									    num_labels=UpperCamelCase_   ,						pad_token_id=UpperCamelCase_   ,						bos_token_id=UpperCamelCase_   ,						eos_token_id=UpperCamelCase_   ,						is_encoder_decoder=UpperCamelCase_   ,						decoder_start_token_id=UpperCamelCase_   ,						forced_eos_token_id=UpperCamelCase_   ,						**UpperCamelCase_   ,						)

									# ensure backward compatibility for BART CNN models
									if self.forced_bos_token_id is None and kwargs.get("force_bos_token_to_be_generated"   ,						UpperCamelCase_):
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.bos_token_id
															warnings.warn(
															    F"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
															    "The config can simply be saved and uploaded again to be fixed.")







class   __lowercase				( __lowerCamelCase	):




			"""simple docstring"""







			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									if self.task in ["default", "seq2seq-lm"]:
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       OrderedDict(
															    [
															        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
															        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
															    ])

															if self.use_past:
																					SCREAMING_SNAKE_CASE_: Optional[int]  		=       {0: "batch"}
																					SCREAMING_SNAKE_CASE_: Any  		=       {0: "batch", 1: "past_decoder_sequence + sequence"}
															else:
																					SCREAMING_SNAKE_CASE_: Dict  		=       {0: "batch", 1: "decoder_sequence"}
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       {0: "batch", 1: "decoder_sequence"}

															if self.use_past:
																					self.fill_with_past_key_values_(UpperCamelCase_   ,						direction="inputs")
									elif self.task == "causal-lm":
															# TODO: figure this case out.
															SCREAMING_SNAKE_CASE_: List[str]  		=       OrderedDict(
															    [
															        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
															        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
															    ])
															if self.use_past:
																					SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[Any]  		=       self.num_layers
																					for i in range(UpperCamelCase_):
																											SCREAMING_SNAKE_CASE_: Dict  		=       {0: "batch", 2: "past_sequence + sequence"}
																											SCREAMING_SNAKE_CASE_: Dict  		=       {0: "batch", 2: "past_sequence + sequence"}
									else:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       OrderedDict(
															    [
															        ("input_ids", {0: "batch", 1: "encoder_sequence"}),
															        ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
															        ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
															        ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
															    ])

									return common_inputs



			@property
			def        _SCREAMING_SNAKE_CASE			( self  :     Dict):
									if self.task in ["default", "seq2seq-lm"]:
															SCREAMING_SNAKE_CASE_: Tuple  		=       super().outputs
									else:
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       super(UpperCamelCase_   ,						self).outputs
															if self.use_past:
																					SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.num_layers
																					for i in range(UpperCamelCase_):
																											SCREAMING_SNAKE_CASE_: List[Any]  		=       {0: "batch", 2: "past_sequence + sequence"}
																											SCREAMING_SNAKE_CASE_: Any  		=       {0: "batch", 2: "past_sequence + sequence"}
									return common_outputs



			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple   ,						lowerCAmelCase__  :     PreTrainedTokenizer   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     bool = False   ,						lowerCAmelCase__  :     Optional[TensorType] = None   ,						):
									SCREAMING_SNAKE_CASE_: Any  		=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_)

									# Generate decoder inputs
									SCREAMING_SNAKE_CASE_: Dict  		=       seq_length if not self.use_past else 1
									SCREAMING_SNAKE_CASE_: Tuple  		=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_)
									SCREAMING_SNAKE_CASE_: str  		=       {F"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       dict(**UpperCamelCase_   ,						**UpperCamelCase_)

									if self.use_past:
															if not is_torch_available():
																					raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
															else:
																					import torch
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[Any]  		=       common_inputs["input_ids"].shape
															SCREAMING_SNAKE_CASE_: List[str]  		=       common_inputs["decoder_input_ids"].shape[1]
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       self.num_attention_heads
															SCREAMING_SNAKE_CASE_: Dict  		=       (
															    batch,
															    num_encoder_attention_heads,
															    encoder_seq_length,
															    self._config.hidden_size // num_encoder_attention_heads,
															)
															SCREAMING_SNAKE_CASE_: str  		=       decoder_seq_length + 3
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       (
															    batch,
															    num_decoder_attention_heads,
															    decoder_past_length,
															    self._config.hidden_size // num_decoder_attention_heads,
															)

															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.cat(
															    [common_inputs["decoder_attention_mask"], torch.ones(UpperCamelCase_   ,						UpperCamelCase_)]   ,						dim=1)

															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       []
															# If the number of encoder and decoder layers are present in the model configuration, both are considered
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.num_layers
															SCREAMING_SNAKE_CASE_: Tuple  		=       min(UpperCamelCase_   ,						UpperCamelCase_)
															SCREAMING_SNAKE_CASE_: int  		=       max(UpperCamelCase_   ,						UpperCamelCase_) - min_num_layers
															SCREAMING_SNAKE_CASE_: Dict  		=       "encoder" if num_encoder_layers > num_decoder_layers else "decoder"

															for _ in range(UpperCamelCase_):
																					common_inputs["past_key_values"].append(
																					    (
																					        torch.zeros(UpperCamelCase_),
																					        torch.zeros(UpperCamelCase_),
																					        torch.zeros(UpperCamelCase_),
																					        torch.zeros(UpperCamelCase_),
																					    ))
															# TODO: test this.
															SCREAMING_SNAKE_CASE_: Tuple  		=       encoder_shape if remaining_side_name == "encoder" else decoder_shape
															for _ in range(UpperCamelCase_   ,						UpperCamelCase_):
																					common_inputs["past_key_values"].append((torch.zeros(UpperCamelCase_), torch.zeros(UpperCamelCase_)))
									return common_inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     PreTrainedTokenizer   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     bool = False   ,						lowerCAmelCase__  :     Optional[TensorType] = None   ,						):
									SCREAMING_SNAKE_CASE_: Any  		=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
									    UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_)

									if self.use_past:
															if not is_torch_available():
																					raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
															else:
																					import torch
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       common_inputs["input_ids"].shape
															# Not using the same length for past_key_values
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       seqlen + 2
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.num_layers
															SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: int  		=       self.num_attention_heads
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       (
															    batch,
															    num_encoder_attention_heads,
															    past_key_values_length,
															    self._config.hidden_size // num_encoder_attention_heads,
															)

															SCREAMING_SNAKE_CASE_: List[Any]  		=       common_inputs["attention_mask"].dtype
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       torch.cat(
															    [common_inputs["attention_mask"], torch.ones(UpperCamelCase_   ,						UpperCamelCase_   ,						dtype=UpperCamelCase_)]   ,						dim=1)
															SCREAMING_SNAKE_CASE_: Tuple  		=       [
															    (torch.zeros(UpperCamelCase_), torch.zeros(UpperCamelCase_)) for _ in range(UpperCamelCase_)
															]
									return common_inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]   ,						lowerCAmelCase__  :     PreTrainedTokenizer   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     bool = False   ,						lowerCAmelCase__  :     Optional[TensorType] = None   ,						):
									# Copied from OnnxConfig.generate_dummy_inputs
									# Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
									# If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       compute_effective_axis_dimension(
									    UpperCamelCase_   ,						fixed_dimension=OnnxConfig.default_fixed_batch   ,						num_token_to_add=0)

									# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       tokenizer.num_special_tokens_to_add(UpperCamelCase_)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       compute_effective_axis_dimension(
									    UpperCamelCase_   ,						fixed_dimension=OnnxConfig.default_fixed_sequence   ,						num_token_to_add=UpperCamelCase_)

									# Generate dummy inputs according to compute batch and sequence
									SCREAMING_SNAKE_CASE_: List[Any]  		=       [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
									SCREAMING_SNAKE_CASE_: Any  		=       dict(tokenizer(UpperCamelCase_   ,						return_tensors=UpperCamelCase_))
									return common_inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]   ,						lowerCAmelCase__  :     PreTrainedTokenizer   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     int = -1   ,						lowerCAmelCase__  :     bool = False   ,						lowerCAmelCase__  :     Optional[TensorType] = None   ,						):
									if self.task in ["default", "seq2seq-lm"]:
															SCREAMING_SNAKE_CASE_: List[str]  		=       self._generate_dummy_inputs_for_default_and_seqaseq_lm(
															    UpperCamelCase_   ,						batch_size=UpperCamelCase_   ,						seq_length=UpperCamelCase_   ,						is_pair=UpperCamelCase_   ,						framework=UpperCamelCase_)

									elif self.task == "causal-lm":
															SCREAMING_SNAKE_CASE_: Dict  		=       self._generate_dummy_inputs_for_causal_lm(
															    UpperCamelCase_   ,						batch_size=UpperCamelCase_   ,						seq_length=UpperCamelCase_   ,						is_pair=UpperCamelCase_   ,						framework=UpperCamelCase_)
									else:
															SCREAMING_SNAKE_CASE_: List[Any]  		=       self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
															    UpperCamelCase_   ,						batch_size=UpperCamelCase_   ,						seq_length=UpperCamelCase_   ,						is_pair=UpperCamelCase_   ,						framework=UpperCamelCase_)

									return common_inputs




			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     Tuple):
									if self.task in ["default", "seq2seq-lm"]:
															SCREAMING_SNAKE_CASE_: int  		=       super()._flatten_past_key_values_(UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_)
									else:
															SCREAMING_SNAKE_CASE_: List[str]  		=       super(UpperCamelCase_   ,						self)._flatten_past_key_values_(
															    UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_   ,						UpperCamelCase_)












import json
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
)
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402
from test_module.custom_feature_extraction import CustomFeatureExtractor  # noqa E402


UpperCAmelCase_									=	get_tests_dir('fixtures')
UpperCAmelCase_									=	get_tests_dir('fixtures/dummy_feature_extractor_config.json')
UpperCAmelCase_									=	get_tests_dir('fixtures/dummy-config.json')





class     lowerCamelCase__(					unittest.TestCase):
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						0
      def 			lowerCAmelCase__						(				self: List[str]   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""facebook/wav2vec2-base-960h"""   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int   ):
             with tempfile.TemporaryDirectory() as tmpdirname:
                    __lowerCamelCase   =						WavaVecaConfig()

                    # remove feature_extractor_type to make sure config.json alone is enough to load feature processor locally
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   ).to_dict()

                    config_dict.pop("""feature_extractor_type"""   )
                    __lowerCamelCase   =						WavaVecaFeatureExtractor(**UpperCamelCase_   )

                    # save in new folder
                    model_config.save_pretrained(UpperCamelCase_   )
                    config.save_pretrained(UpperCamelCase_   )

                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )

                    # make sure private variable is not incorrectly saved
                    __lowerCamelCase   =						json.loads(config.to_json_string()   )
                    self.assertTrue("""_processor_class""" not in dict_as_saved   )

             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
             self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       """bert-base is not a local folder and is not a valid model identifier"""   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""bert-base"""   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_    ,       revision="""aaaaaa"""   )
      def 			lowerCAmelCase__						(				self: Optional[Any]   ):
             with self.assertRaisesRegex(
                 UpperCamelCase_    ,       """hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json."""    ,       ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained("""hf-internal-testing/config-no-model"""   )
      def 			lowerCAmelCase__						(				self: Tuple   ):
             # If remote code is not set, we will time out when asking whether to load the model.
             with self.assertRaises(UpperCamelCase_   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""   )
             # If remote code is disabled, we can't load this config.
             with self.assertRaises(UpperCamelCase_   ):
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )

             __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                 """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
             self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )

             # Test feature extractor can be reloaded.
             with tempfile.TemporaryDirectory() as tmp_dir:
                    feature_extractor.save_pretrained(UpperCamelCase_   )
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_    ,       trust_remote_code=UpperCamelCase_   )
             self.assertEqual(reloaded_feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
      def 			lowerCAmelCase__						(				self: Any   ):
             try:
                    AutoConfig.register("""custom"""    ,       UpperCamelCase_   )
                    AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )
                    # Trying to register something existing in the Transformers library will raise an error
                    with self.assertRaises(UpperCamelCase_   ):
                           AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )

                    # Now that the config is registered, it can be used as any other config with the auto-API
                    __lowerCamelCase   =						CustomFeatureExtractor.from_pretrained(UpperCamelCase_   )
                    with tempfile.TemporaryDirectory() as tmp_dir:
                           feature_extractor.save_pretrained(UpperCamelCase_   )
                           __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(UpperCamelCase_   )
                           self.assertIsInstance(UpperCamelCase_    ,       UpperCamelCase_   )

             finally:
                    if "custom" in CONFIG_MAPPING._extra_content:
                           del CONFIG_MAPPING._extra_content["custom"]
                    if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                           del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]




      def 			lowerCAmelCase__						(				self: Dict   ):





             class     lowerCamelCase__(					__lowerCamelCase):
                   UpperCAmelCase__      :	str    		=   True

             try:
                    AutoConfig.register("""custom"""    ,       UpperCamelCase_   )
                    AutoFeatureExtractor.register(UpperCamelCase_    ,       UpperCamelCase_   )
                    # If remote code is not set, the default is to use local
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(feature_extractor.is_local   )

                    # If remote code is disabled, we load the local one.
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(feature_extractor.is_local   )

                    # If remote is enabled, we load from the Hub
                    __lowerCamelCase   =						AutoFeatureExtractor.from_pretrained(
                        """hf-internal-testing/test_dynamic_feature_extractor"""    ,       trust_remote_code=UpperCamelCase_   )
                    self.assertEqual(feature_extractor.__class__.__name__    ,       """NewFeatureExtractor"""   )
                    self.assertTrue(not hasattr(UpperCamelCase_    ,       """is_local"""   )   )

             finally:
                    if "custom" in CONFIG_MAPPING._extra_content:
                           del CONFIG_MAPPING._extra_content["custom"]
                    if CustomConfig in FEATURE_EXTRACTOR_MAPPING._extra_content:
                           del FEATURE_EXTRACTOR_MAPPING._extra_content[CustomConfig]

