
'''simple docstring'''




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


lowercase			:				int    		=			logging.get_logger(__name__)

lowercase			:				List[str]    		=			{
    '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  A				(							__snake_case						):
     __magic_name__						=		'''bart'''
     __magic_name__						=		['''past_key_values''']
     __magic_name__						=		{'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}





     def __init__(							self						,			SCREAMING_SNAKE_CASE=50265						,			SCREAMING_SNAKE_CASE=1024						,			SCREAMING_SNAKE_CASE=12						,			SCREAMING_SNAKE_CASE=4096						,			SCREAMING_SNAKE_CASE=16						,			SCREAMING_SNAKE_CASE=12						,			SCREAMING_SNAKE_CASE=4096						,			SCREAMING_SNAKE_CASE=16						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE="gelu"						,			SCREAMING_SNAKE_CASE=1024						,			SCREAMING_SNAKE_CASE=0.1						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE=0.02						,			SCREAMING_SNAKE_CASE=0.0						,			SCREAMING_SNAKE_CASE=False						,			SCREAMING_SNAKE_CASE=True						,			SCREAMING_SNAKE_CASE=3						,			SCREAMING_SNAKE_CASE=1						,			SCREAMING_SNAKE_CASE=0						,			SCREAMING_SNAKE_CASE=2						,			SCREAMING_SNAKE_CASE=True						,			SCREAMING_SNAKE_CASE=2						,			SCREAMING_SNAKE_CASE=2						,			**SCREAMING_SNAKE_CASE						,			) ->				Optional[int]:






         """simple docstring"""






         A       :   Dict					=						vocab_size
         A       :   Any					=						max_position_embeddings
         A       :   Union[str, Any]					=						d_model
         A       :   str					=						encoder_ffn_dim
         A       :   Dict					=						encoder_layers
         A       :   str					=						encoder_attention_heads
         A       :   Union[str, Any]					=						decoder_ffn_dim
         A       :   Optional[Any]					=						decoder_layers
         A       :   List[Any]					=						decoder_attention_heads
         A       :   Optional[int]					=						dropout
         A       :   Optional[int]					=						attention_dropout
         A       :   Optional[int]					=						activation_dropout
         A       :   Dict					=						activation_function
         A       :   List[str]					=						init_std
         A       :   Any					=						encoder_layerdrop
         A       :   List[Any]					=						decoder_layerdrop
         A       :   List[str]					=						classifier_dropout
         A       :   Any					=						use_cache
         A       :   Optional[Any]					=						encoder_layers
         A       :   Tuple					=						scale_embedding  # scale factor will be sqrt(d_model) if True

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

         # ensure backward compatibility for BART CNN models
         if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated'''						,			SCREAMING_SNAKE_CASE	):
             A       :   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  A				(							__snake_case						):





     @property
     def 				__lowerCAmelCase							(							self	) ->				Mapping[str, Mapping[int, str]]:






         """simple docstring"""






         if self.task in ["default", "seq2seq-lm"]:
             A       :   Dict					=						OrderedDict(
                 [
                     ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                     ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
                 ]	)

             if self.use_past:
                 A       :   Optional[int]					=						{0: '''batch'''}
                 A       :   Optional[int]					=						{0: '''batch''', 1: '''past_decoder_sequence + sequence'''}
             else:
                 A       :   str					=						{0: '''batch''', 1: '''decoder_sequence'''}
                 A       :   Optional[int]					=						{0: '''batch''', 1: '''decoder_sequence'''}

             if self.use_past:
                 self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE						,			direction='''inputs'''	)
         elif self.task == "causal-lm":
             # TODO: figure this case out.
             A       :   List[Any]					=						OrderedDict(
                 [
                     ('''input_ids''', {0: '''batch''', 1: '''encoder_sequence'''}),
                     ('''attention_mask''', {0: '''batch''', 1: '''encoder_sequence'''}),
                 ]	)
             if self.use_past:
                 A,  A       :   Tuple					=						self.num_layers
                 for i in range(SCREAMING_SNAKE_CASE	):
                     A       :   Optional[Any]					=						{0: '''batch''', 2: '''past_sequence + sequence'''}
                     A       :   int					=						{0: '''batch''', 2: '''past_sequence + sequence'''}
         else:
             A       :   Tuple					=						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 				__lowerCAmelCase							(							self	) ->				Mapping[str, Mapping[int, str]]:






         """simple docstring"""






         if self.task in ["default", "seq2seq-lm"]:
             A       :   str					=						super().outputs
         else:
             A       :   Tuple					=						super(SCREAMING_SNAKE_CASE						,			self	).outputs
             if self.use_past:
                 A,  A       :   Any					=						self.num_layers
                 for i in range(SCREAMING_SNAKE_CASE	):
                     A       :   List[Any]					=						{0: '''batch''', 2: '''past_sequence + sequence'''}
                     A       :   List[str]					=						{0: '''batch''', 2: '''past_sequence + sequence'''}
         return common_outputs





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = None						,			) ->				Mapping[str, Any]:






         """simple docstring"""






         A       :   int					=						self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         # Generate decoder inputs
         A       :   Union[str, Any]					=						seq_length if not self.use_past else 1
         A       :   Union[str, Any]					=						self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         A       :   Union[str, Any]					=						{F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
         A       :   Union[str, Any]					=						dict(**SCREAMING_SNAKE_CASE						,			**SCREAMING_SNAKE_CASE	)

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

             A       :   Union[str, Any]					=						torch.cat(
                 [common_inputs['''decoder_attention_mask'''], torch.ones(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)]						,			dim=1	)

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

             for _ in range(SCREAMING_SNAKE_CASE	):
                 common_inputs["past_key_values"].append(
                     (
                         torch.zeros(SCREAMING_SNAKE_CASE	),
                         torch.zeros(SCREAMING_SNAKE_CASE	),
                         torch.zeros(SCREAMING_SNAKE_CASE	),
                         torch.zeros(SCREAMING_SNAKE_CASE	),
                     )	)
             # TODO: test this.
             A       :   List[str]					=						encoder_shape if remaining_side_name == '''encoder''' else decoder_shape
             for _ in range(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	):
                 common_inputs["past_key_values"].append((torch.zeros(SCREAMING_SNAKE_CASE	), torch.zeros(SCREAMING_SNAKE_CASE	))	)
         return common_inputs





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = None						,			) ->				Mapping[str, Any]:






         """simple docstring"""






         A       :   Optional[int]					=						self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
             SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

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

             A       :   Union[str, Any]					=						common_inputs['''attention_mask'''].dtype
             A       :   List[Any]					=						torch.cat(
                 [common_inputs['''attention_mask'''], torch.ones(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			dtype=SCREAMING_SNAKE_CASE	)]						,			dim=1	)
             A       :   Tuple					=						[
                 (torch.zeros(SCREAMING_SNAKE_CASE	), torch.zeros(SCREAMING_SNAKE_CASE	)) for _ in range(SCREAMING_SNAKE_CASE	)
             ]
         return common_inputs





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = None						,			) ->				Mapping[str, Any]:






         """simple docstring"""






         A       :   Tuple					=						compute_effective_axis_dimension(
             SCREAMING_SNAKE_CASE						,			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
         A       :   int					=						tokenizer.num_special_tokens_to_add(SCREAMING_SNAKE_CASE	)
         A       :   int					=						compute_effective_axis_dimension(
             SCREAMING_SNAKE_CASE						,			fixed_dimension=OnnxConfig.default_fixed_sequence						,			num_token_to_add=SCREAMING_SNAKE_CASE	)

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





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = -1						,			SCREAMING_SNAKE_CASE = False						,			SCREAMING_SNAKE_CASE = None						,			) ->				Mapping[str, Any]:






         """simple docstring"""






         if self.task in ["default", "seq2seq-lm"]:
             A       :   Tuple					=						self._generate_dummy_inputs_for_default_and_seqaseq_lm(
                 SCREAMING_SNAKE_CASE						,			batch_size=SCREAMING_SNAKE_CASE						,			seq_length=SCREAMING_SNAKE_CASE						,			is_pair=SCREAMING_SNAKE_CASE						,			framework=SCREAMING_SNAKE_CASE	)

         elif self.task == "causal-lm":
             A       :   int					=						self._generate_dummy_inputs_for_causal_lm(
                 SCREAMING_SNAKE_CASE						,			batch_size=SCREAMING_SNAKE_CASE						,			seq_length=SCREAMING_SNAKE_CASE						,			is_pair=SCREAMING_SNAKE_CASE						,			framework=SCREAMING_SNAKE_CASE	)
         else:
             A       :   Dict					=						self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
                 SCREAMING_SNAKE_CASE						,			batch_size=SCREAMING_SNAKE_CASE						,			seq_length=SCREAMING_SNAKE_CASE						,			is_pair=SCREAMING_SNAKE_CASE						,			framework=SCREAMING_SNAKE_CASE	)

         return common_inputs





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				List[str]:






         """simple docstring"""






         if self.task in ["default", "seq2seq-lm"]:
             A       :   List[str]					=						super()._flatten_past_key_values_(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         else:
             A       :   Optional[Any]					=						super(SCREAMING_SNAKE_CASE						,			self	)._flatten_past_key_values_(
                 SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)






'''simple docstring'''




import json
import os
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import copyfile

from huggingface_hub import HfFolder, Repository, create_repo, delete_repo
from requests.exceptions import HTTPError

import transformers
from transformers import (
    CONFIG_MAPPING,
    FEATURE_EXTRACTOR_MAPPING,
    PROCESSOR_MAPPING,
    TOKENIZER_MAPPING,
    AutoConfig,
    AutoFeatureExtractor,
    AutoProcessor,
    AutoTokenizer,
    BertTokenizer,
    ProcessorMixin,
    WavaVecaConfig,
    WavaVecaFeatureExtractor,
    WavaVecaProcessor,
)
from transformers.testing_utils import TOKEN, USER, get_tests_dir, is_staging_test
from transformers.tokenization_utils import TOKENIZER_CONFIG_FILE
from transformers.utils import FEATURE_EXTRACTOR_NAME, is_tokenizers_available


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
from test_module.custom_processing import CustomProcessor  # noqa E402
from test_module.custom_tokenization import CustomTokenizer  # noqa E402


lowercase			:				str    		=			get_tests_dir('fixtures/dummy_feature_extractor_config.json')
lowercase			:				str    		=			get_tests_dir('fixtures/vocab.json')
lowercase			:				int    		=			get_tests_dir('fixtures')





class  A				(							unittest.TestCase						):
     __magic_name__						=		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         A       :   Tuple					=						0





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   List[Any]					=						AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''	)
         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             A       :   Union[str, Any]					=						WavaVecaConfig()
             A       :   List[str]					=						AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''	)

             # save in new folder
             model_config.save_pretrained(SCREAMING_SNAKE_CASE	)
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             A       :   List[str]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             # copy relevant files
             copyfile(SCREAMING_SNAKE_CASE						,			os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)	)
             copyfile(SCREAMING_SNAKE_CASE						,			os.path.join(SCREAMING_SNAKE_CASE						,			'''vocab.json'''	)	)

             A       :   Optional[Any]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Union[str, Any]:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             A       :   Dict					=						WavaVecaFeatureExtractor()
             A       :   List[str]					=						AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''	)

             A       :   str					=						WavaVecaProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             # save in new folder
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             # drop `processor_class` in tokenizer
             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''r'''	) as f:
                 A       :   Dict					=						json.load(SCREAMING_SNAKE_CASE	)
                 config_dict.pop('''processor_class'''	)

             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''w'''	) as f:
                 f.write(json.dumps(SCREAMING_SNAKE_CASE	)	)

             A       :   Optional[Any]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             A       :   List[Any]					=						WavaVecaFeatureExtractor()
             A       :   List[Any]					=						AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''	)

             A       :   str					=						WavaVecaProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             # save in new folder
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             # drop `processor_class` in feature extractor
             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''r'''	) as f:
                 A       :   str					=						json.load(SCREAMING_SNAKE_CASE	)
                 config_dict.pop('''processor_class'''	)

             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''w'''	) as f:
                 f.write(json.dumps(SCREAMING_SNAKE_CASE	)	)

             A       :   str					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[Any]:






         """simple docstring"""






         with tempfile.TemporaryDirectory() as tmpdirname:
             A       :   str					=						WavaVecaConfig(processor_class='''Wav2Vec2Processor'''	)
             model_config.save_pretrained(SCREAMING_SNAKE_CASE	)
             # copy relevant files
             copyfile(SCREAMING_SNAKE_CASE						,			os.path.join(SCREAMING_SNAKE_CASE						,			'''vocab.json'''	)	)
             # create emtpy sample processor
             with open(os.path.join(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)						,			'''w'''	) as f:
                 f.write('''{}'''	)

             A       :   List[str]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Any:






         """simple docstring"""






         with self.assertRaises(SCREAMING_SNAKE_CASE	):
             A       :   Optional[Any]					=						AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''	)
         # If remote code is disabled, we can't load this config.
         with self.assertRaises(SCREAMING_SNAKE_CASE	):
             A       :   Union[str, Any]					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)

         A       :   Union[str, Any]					=						AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
         self.assertTrue(processor.special_attribute_present	)
         self.assertEqual(processor.__class__.__name__						,			'''NewProcessor'''	)

         A       :   List[str]					=						processor.feature_extractor
         self.assertTrue(feature_extractor.special_attribute_present	)
         self.assertEqual(feature_extractor.__class__.__name__						,			'''NewFeatureExtractor'''	)

         A       :   Tuple					=						processor.tokenizer
         self.assertTrue(tokenizer.special_attribute_present	)
         if is_tokenizers_available():
             self.assertEqual(tokenizer.__class__.__name__						,			'''NewTokenizerFast'''	)

             # Test we can also load the slow version
             A       :   List[str]					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE						,			use_fast=SCREAMING_SNAKE_CASE	)
             A       :   int					=						new_processor.tokenizer
             self.assertTrue(new_tokenizer.special_attribute_present	)
             self.assertEqual(new_tokenizer.__class__.__name__						,			'''NewTokenizer'''	)
         else:
             self.assertEqual(tokenizer.__class__.__name__						,			'''NewTokenizer'''	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[Any]:






         """simple docstring"""






         try:
             AutoConfig.register('''custom'''						,			SCREAMING_SNAKE_CASE	)
             AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             AutoTokenizer.register(SCREAMING_SNAKE_CASE						,			slow_tokenizer_class=SCREAMING_SNAKE_CASE	)
             AutoProcessor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             # Trying to register something existing in the Transformers library will raise an error
             with self.assertRaises(SCREAMING_SNAKE_CASE	):
                 AutoProcessor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             # Now that the config is registered, it can be used as any other config with the auto-API
             A       :   List[Any]					=						CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE	)

             with tempfile.TemporaryDirectory() as tmp_dir:
                 A       :   Tuple					=						os.path.join(SCREAMING_SNAKE_CASE						,			'''vocab.txt'''	)
                 with open(SCREAMING_SNAKE_CASE						,			'''w'''						,			encoding='''utf-8'''	) as vocab_writer:
                     vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]	)	)
                 A       :   Optional[int]					=						CustomTokenizer(SCREAMING_SNAKE_CASE	)

             A       :   Any					=						CustomProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

             with tempfile.TemporaryDirectory() as tmp_dir:
                 processor.save_pretrained(SCREAMING_SNAKE_CASE	)
                 A       :   List[str]					=						AutoProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)
                 self.assertIsInstance(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         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]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                 del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                 del PROCESSOR_MAPPING._extra_content[CustomConfig]





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         class  A				(							__snake_case						):
              __magic_name__						=		False





         class  A				(							__snake_case						):
              __magic_name__						=		False





         class  A				(							__snake_case						):
              __magic_name__						=		'''AutoFeatureExtractor'''
              __magic_name__						=		'''AutoTokenizer'''
              __magic_name__						=		False

         try:
             AutoConfig.register('''custom'''						,			SCREAMING_SNAKE_CASE	)
             AutoFeatureExtractor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             AutoTokenizer.register(SCREAMING_SNAKE_CASE						,			slow_tokenizer_class=SCREAMING_SNAKE_CASE	)
             AutoProcessor.register(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
             # If remote code is not set, the default is to use local classes.
             A       :   Union[str, Any]					=						AutoProcessor.from_pretrained('''hf-internal-testing/test_dynamic_processor'''	)
             self.assertEqual(processor.__class__.__name__						,			'''NewProcessor'''	)
             self.assertFalse(processor.special_attribute_present	)
             self.assertFalse(processor.feature_extractor.special_attribute_present	)
             self.assertFalse(processor.tokenizer.special_attribute_present	)

             # If remote code is disabled, we load the local ones.
             A       :   Optional[int]					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
             self.assertEqual(processor.__class__.__name__						,			'''NewProcessor'''	)
             self.assertFalse(processor.special_attribute_present	)
             self.assertFalse(processor.feature_extractor.special_attribute_present	)
             self.assertFalse(processor.tokenizer.special_attribute_present	)

             # If remote is enabled, we load from the Hub.
             A       :   Tuple					=						AutoProcessor.from_pretrained(
                 '''hf-internal-testing/test_dynamic_processor'''						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
             self.assertEqual(processor.__class__.__name__						,			'''NewProcessor'''	)
             self.assertTrue(processor.special_attribute_present	)
             self.assertTrue(processor.feature_extractor.special_attribute_present	)
             self.assertTrue(processor.tokenizer.special_attribute_present	)

         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]
             if CustomConfig in TOKENIZER_MAPPING._extra_content:
                 del TOKENIZER_MAPPING._extra_content[CustomConfig]
             if CustomConfig in PROCESSOR_MAPPING._extra_content:
                 del PROCESSOR_MAPPING._extra_content[CustomConfig]





     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






         A       :   int					=						AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-bert'''	)
         self.assertEqual(processor.__class__.__name__						,			'''BertTokenizerFast'''	)





     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






         A       :   Optional[int]					=						AutoProcessor.from_pretrained('''hf-internal-testing/tiny-random-convnext'''	)
         self.assertEqual(processor.__class__.__name__						,			'''ConvNextImageProcessor'''	)





@is_staging_test
class  A				(							unittest.TestCase						):
     __magic_name__						=		['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''bla''', '''blou''']





     @classmethod
     def 				__lowerCAmelCase							(							cls	) ->				Dict:






         """simple docstring"""






         A       :   Optional[int]					=						TOKEN
         HfFolder.save_token(SCREAMING_SNAKE_CASE	)





     @classmethod
     def 				__lowerCAmelCase							(							cls	) ->				Any:






         """simple docstring"""






         try:
             delete_repo(token=cls._token						,			repo_id='''test-processor'''	)
         except HTTPError:
             pass

         try:
             delete_repo(token=cls._token						,			repo_id='''valid_org/test-processor-org'''	)
         except HTTPError:
             pass

         try:
             delete_repo(token=cls._token						,			repo_id='''test-dynamic-processor'''	)
         except HTTPError:
             pass





     def 				__lowerCAmelCase							(							self	) ->				Dict:






         """simple docstring"""






         A       :   Union[str, Any]					=						WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)
         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(SCREAMING_SNAKE_CASE						,			'''test-processor'''	)						,			push_to_hub=SCREAMING_SNAKE_CASE						,			use_auth_token=self._token	)

             A       :   int					=						WavaVecaProcessor.from_pretrained(F'{USER}/test-processor'	)
             for k, v in processor.feature_extractor.__dict__.items():
                 self.assertEqual(SCREAMING_SNAKE_CASE						,			getattr(new_processor.feature_extractor						,			SCREAMING_SNAKE_CASE	)	)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()						,			processor.tokenizer.get_vocab()	)





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   Tuple					=						WavaVecaProcessor.from_pretrained(SCREAMING_SNAKE_CASE	)

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(
                 os.path.join(SCREAMING_SNAKE_CASE						,			'''test-processor-org'''	)						,			push_to_hub=SCREAMING_SNAKE_CASE						,			use_auth_token=self._token						,			organization='''valid_org'''						,			)

             A       :   int					=						WavaVecaProcessor.from_pretrained('''valid_org/test-processor-org'''	)
             for k, v in processor.feature_extractor.__dict__.items():
                 self.assertEqual(SCREAMING_SNAKE_CASE						,			getattr(new_processor.feature_extractor						,			SCREAMING_SNAKE_CASE	)	)
             self.assertDictEqual(new_processor.tokenizer.get_vocab()						,			processor.tokenizer.get_vocab()	)





     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






         CustomFeatureExtractor.register_for_auto_class()
         CustomTokenizer.register_for_auto_class()
         CustomProcessor.register_for_auto_class()

         A       :   Any					=						CustomFeatureExtractor.from_pretrained(SCREAMING_SNAKE_CASE	)

         with tempfile.TemporaryDirectory() as tmp_dir:
             A       :   Union[str, Any]					=						os.path.join(SCREAMING_SNAKE_CASE						,			'''vocab.txt'''	)
             with open(SCREAMING_SNAKE_CASE						,			'''w'''						,			encoding='''utf-8'''	) as vocab_writer:
                 vocab_writer.write(''''''.join([x + '''\n''' for x in self.vocab_tokens]	)	)
             A       :   str					=						CustomTokenizer(SCREAMING_SNAKE_CASE	)

         A       :   Union[str, Any]					=						CustomProcessor(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)

         with tempfile.TemporaryDirectory() as tmp_dir:
             create_repo(F'{USER}/test-dynamic-processor'						,			token=self._token	)
             A       :   List[str]					=						Repository(SCREAMING_SNAKE_CASE						,			clone_from=F'{USER}/test-dynamic-processor'						,			token=self._token	)
             processor.save_pretrained(SCREAMING_SNAKE_CASE	)

             # This has added the proper auto_map field to the feature extractor config
             self.assertDictEqual(
                 processor.feature_extractor.auto_map						,			{
                     '''AutoFeatureExtractor''': '''custom_feature_extraction.CustomFeatureExtractor''',
                     '''AutoProcessor''': '''custom_processing.CustomProcessor''',
                 }						,			)

             # This has added the proper auto_map field to the tokenizer config
             with open(os.path.join(SCREAMING_SNAKE_CASE						,			'''tokenizer_config.json'''	)	) as f:
                 A       :   Dict					=						json.load(SCREAMING_SNAKE_CASE	)
             self.assertDictEqual(
                 tokenizer_config['''auto_map''']						,			{
                     '''AutoTokenizer''': ['''custom_tokenization.CustomTokenizer''', None],
                     '''AutoProcessor''': '''custom_processing.CustomProcessor''',
                 }						,			)

             # The code has been copied from fixtures
             self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE						,			'''custom_feature_extraction.py'''	)	)	)
             self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE						,			'''custom_tokenization.py'''	)	)	)
             self.assertTrue(os.path.isfile(os.path.join(SCREAMING_SNAKE_CASE						,			'''custom_processing.py'''	)	)	)

             repo.push_to_hub()

         A       :   Optional[int]					=						AutoProcessor.from_pretrained(F'{USER}/test-dynamic-processor'						,			trust_remote_code=SCREAMING_SNAKE_CASE	)
         # Can't make an isinstance check because the new_processor is from the CustomProcessor class of a dynamic module
         self.assertEqual(new_processor.__class__.__name__						,			'''CustomProcessor'''	)




