"""simple docstring"""



import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import datasets
import evaluate
import numpy as np
from datasets import load_dataset

import transformers
from transformers import (
    AutoConfig,
    AutoModelForSequenceClassification,
    AutoTokenizer,
    DataCollatorWithPadding,
    EvalPrediction,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version


# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")

__magic_name__     					=       logging.getLogger(__name__)

@dataclass
class SCREAMING_SNAKE_CASE  :







 """simple docstring"""


 a_							:						Tuple	      =field(
     default=1_2_8 ,   metadata={
         "help": (
             "The maximum total input sequence length after tokenization. Sequences longer "
             "than this will be truncated, sequences shorter will be padded."
         )
     } ,   )
 a_							:						Tuple	      =field(
     default=_a ,   metadata={"help": "Overwrite the cached preprocessed datasets or not."}						)
 a_							:						Any	      =field(
     default=_a ,   metadata={
         "help": (
             "Whether to pad all samples to `max_seq_length`. "
             "If False, will pad the samples dynamically when batching to the maximum length in the batch."
         )
     } ,   )
 a_							:						str	      =field(
     default=_a ,   metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of training examples to this "
             "value if set."
         )
     } ,   )
 a_							:						Any	      =field(
     default=_a ,   metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of evaluation examples to this "
             "value if set."
         )
     } ,   )
 a_							:						int	      =field(
     default=_a ,   metadata={
         "help": (
             "For debugging purposes or quicker training, truncate the number of prediction examples to this "
             "value if set."
         )
     } ,   )

@dataclass
class SCREAMING_SNAKE_CASE  :







 """simple docstring"""


 a_							:						Any	      =field(
     default=_a ,   metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}						)
 a_							:						List[Any]	      =field(
     default=_a ,   metadata={"help": "Evaluation language. Also train language if `train_language` is set to None."}						)
 a_							:						List[Any]	      =field(
     default=_a ,   metadata={"help": "Train language if it is different from the evaluation language."}						)
 a_							:						Union[str, Any]	      =field(
     default=_a ,   metadata={"help": "Pretrained config name or path if not the same as model_name"}						)
 a_							:						List[Any]	      =field(
     default=_a ,   metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"}						)
 a_							:						Optional[Any]	      =field(
     default=_a ,   metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"} ,   )
 a_							:						int	      =field(
     default=_a ,   metadata={"help": "arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"} ,   )
 a_							:						Any	      =field(
     default=_a ,   metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."} ,   )
 a_							:						Tuple	      =field(
     default="main" ,   metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."} ,   )
 a_							:						Any	      =field(
     default=_a ,   metadata={
         "help": (
             "Will use the token generated when running `huggingface-cli login` (necessary to use this script "
             "with private models)."
         )
     } ,   )
 a_							:						List[str]	      =field(
     default=_a ,   metadata={"help": "Will enable to load a pretrained model whose head dimensions are different."} ,   )





def 	_lowerCamelCase			(			)				->  List[Any]:


   '''simple docstring'''


   a__  					=		HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)       )
   a__  					=		parser.parse_args_into_dataclasses()

   # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
   # information sent is the one passed as arguments along with your Python/PyTorch versions.
   send_example_telemetry('run_xnli',UpperCAmelCase__       )

   # Setup logging
   logging.basicConfig(
       format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',datefmt='%m/%d/%Y %H:%M:%S',handlers=[logging.StreamHandler(sys.stdout       )],)

   if training_args.should_log:
      # The default of training_args.log_level is passive, so we set log level at info here to have that default.
      transformers.utils.logging.set_verbosity_info()

   a__  					=		training_args.get_process_log_level()
   logger.setLevel(UpperCAmelCase__       )
   datasets.utils.logging.set_verbosity(UpperCAmelCase__       )
   transformers.utils.logging.set_verbosity(UpperCAmelCase__       )
   transformers.utils.logging.enable_default_handler()
   transformers.utils.logging.enable_explicit_format()

   # Log on each process the small summary:
   logger.warning(
       f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
       + f'''distributed training: {bool(training_args.local_rank != -1       )}, 16-bits training: {training_args.fpaa}'''       )
   logger.info(f'''Training/evaluation parameters {training_args}'''       )

   # Detecting last checkpoint.
   a__  					=		None
   if os.path.isdir(training_args.output_dir       ) and training_args.do_train and not training_args.overwrite_output_dir:
      a__  					=		get_last_checkpoint(training_args.output_dir       )
      if last_checkpoint is None and len(os.listdir(training_args.output_dir       )       ) > 0:
         raise ValueError(
             f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
             'Use --overwrite_output_dir to overcome.'       )
      elif last_checkpoint is not None:
         logger.info(
             f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
             'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'       )

    # Set seed before initializing model.
   set_seed(training_args.seed       )

   # In distributed training, the load_dataset function guarantees that only one local process can concurrently
   # download the dataset.
   # Downloading and loading xnli dataset from the hub.
   if training_args.do_train:
      if model_args.train_language is None:
         a__  					=		load_dataset(
             'xnli',model_args.language,split='train',cache_dir=model_args.cache_dir,use_auth_token=True if model_args.use_auth_token else None,)
      else:
         a__  					=		load_dataset(
             'xnli',model_args.train_language,split='train',cache_dir=model_args.cache_dir,use_auth_token=True if model_args.use_auth_token else None,)
      a__  					=		train_dataset.features["label"].names

   if training_args.do_eval:
      a__  					=		load_dataset(
          'xnli',model_args.language,split='validation',cache_dir=model_args.cache_dir,use_auth_token=True if model_args.use_auth_token else None,)
      a__  					=		eval_dataset.features["label"].names

   if training_args.do_predict:
      a__  					=		load_dataset(
          'xnli',model_args.language,split='test',cache_dir=model_args.cache_dir,use_auth_token=True if model_args.use_auth_token else None,)
      a__  					=		predict_dataset.features["label"].names

   # Labels
   a__  					=		len(UpperCAmelCase__       )

   # Load pretrained model and tokenizer
   # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
   # download model & vocab.
   a__  					=		AutoConfig.from_pretrained(
       model_args.config_name if model_args.config_name else model_args.model_name_or_path,num_labels=UpperCAmelCase__,idalabel={str(UpperCAmelCase__       ): label for i, label in enumerate(UpperCAmelCase__       )},labelaid={label: i for i, label in enumerate(UpperCAmelCase__       )},finetuning_task='xnli',cache_dir=model_args.cache_dir,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,)
   a__  					=		AutoTokenizer.from_pretrained(
       model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path,do_lower_case=model_args.do_lower_case,cache_dir=model_args.cache_dir,use_fast=model_args.use_fast_tokenizer,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,)
   a__  					=		AutoModelForSequenceClassification.from_pretrained(
       model_args.model_name_or_path,from_tf=bool('.ckpt' in model_args.model_name_or_path       ),config=UpperCAmelCase__,cache_dir=model_args.cache_dir,revision=model_args.model_revision,use_auth_token=True if model_args.use_auth_token else None,ignore_mismatched_sizes=model_args.ignore_mismatched_sizes,)

   # Preprocessing the datasets
   # Padding strategy
   if data_args.pad_to_max_length:
      a__  					=		"max_length"
   else:
      # We will pad later, dynamically at batch creation, to the max sequence length in each batch
      a__  					=		False

   def preprocess_function(UpperCAmelCase__       ):
      # Tokenize the texts
      return tokenizer(
          examples['premise'],examples['hypothesis'],padding=UpperCAmelCase__,max_length=data_args.max_seq_length,truncation=UpperCAmelCase__,)

   if training_args.do_train:
      if data_args.max_train_samples is not None:
         a__  					=		min(len(UpperCAmelCase__       ),data_args.max_train_samples       )
         a__  					=		train_dataset.select(range(UpperCAmelCase__       )       )
      with training_args.main_process_first(desc='train dataset map pre-processing'       ):
         a__  					=		train_dataset.map(
             UpperCAmelCase__,batched=UpperCAmelCase__,load_from_cache_file=not data_args.overwrite_cache,desc='Running tokenizer on train dataset',)
      # Log a few random samples from the training set:
      for index in random.sample(range(len(UpperCAmelCase__       )       ),3       ):
         logger.info(f'''Sample {index} of the training set: {train_dataset[index]}.'''       )

   if training_args.do_eval:
      if data_args.max_eval_samples is not None:
         a__  					=		min(len(UpperCAmelCase__       ),data_args.max_eval_samples       )
         a__  					=		eval_dataset.select(range(UpperCAmelCase__       )       )
      with training_args.main_process_first(desc='validation dataset map pre-processing'       ):
         a__  					=		eval_dataset.map(
             UpperCAmelCase__,batched=UpperCAmelCase__,load_from_cache_file=not data_args.overwrite_cache,desc='Running tokenizer on validation dataset',)

   if training_args.do_predict:
      if data_args.max_predict_samples is not None:
         a__  					=		min(len(UpperCAmelCase__       ),data_args.max_predict_samples       )
         a__  					=		predict_dataset.select(range(UpperCAmelCase__       )       )
      with training_args.main_process_first(desc='prediction dataset map pre-processing'       ):
         a__  					=		predict_dataset.map(
             UpperCAmelCase__,batched=UpperCAmelCase__,load_from_cache_file=not data_args.overwrite_cache,desc='Running tokenizer on prediction dataset',)

    # Get the metric function
   a__  					=		evaluate.load('xnli'       )

   # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
   # predictions and label_ids field) and has to return a dictionary string to float.
   def compute_metrics(UpperCAmelCase__       ):
      a__  					=		p.predictions[0] if isinstance(p.predictions,UpperCAmelCase__       ) else p.predictions
      a__  					=		np.argmax(UpperCAmelCase__,axis=1       )
      return metric.compute(predictions=UpperCAmelCase__,references=p.label_ids       )

   # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
   if data_args.pad_to_max_length:
      a__  					=		default_data_collator
   elif training_args.fpaa:
      a__  					=		DataCollatorWithPadding(UpperCAmelCase__,pad_to_multiple_of=8       )
   else:
      a__  					=		None

   # Initialize our Trainer
   a__  					=		Trainer(
       model=UpperCAmelCase__,args=UpperCAmelCase__,train_dataset=train_dataset if training_args.do_train else None,eval_dataset=eval_dataset if training_args.do_eval else None,compute_metrics=UpperCAmelCase__,tokenizer=UpperCAmelCase__,data_collator=UpperCAmelCase__,)

   # Training
   if training_args.do_train:
      a__  					=		None
      if training_args.resume_from_checkpoint is not None:
         a__  					=		training_args.resume_from_checkpoint
      elif last_checkpoint is not None:
         a__  					=		last_checkpoint
      a__  					=		trainer.train(resume_from_checkpoint=UpperCAmelCase__       )
      a__  					=		train_result.metrics
      a__  					=		(
          data_args.max_train_samples if data_args.max_train_samples is not None else len(UpperCAmelCase__       )
      )
      a__  					=		min(UpperCAmelCase__,len(UpperCAmelCase__       )       )

      trainer.save_model()  # Saves the tokenizer too for easy upload

      trainer.log_metrics('train',UpperCAmelCase__       )
      trainer.save_metrics('train',UpperCAmelCase__       )
      trainer.save_state()

   # Evaluation
   if training_args.do_eval:
      logger.info('*** Evaluate ***'       )
      a__  					=		trainer.evaluate(eval_dataset=UpperCAmelCase__       )

      a__  					=		data_args.max_eval_samples if data_args.max_eval_samples is not None else len(UpperCAmelCase__       )
      a__  					=		min(UpperCAmelCase__,len(UpperCAmelCase__       )       )

      trainer.log_metrics('eval',UpperCAmelCase__       )
      trainer.save_metrics('eval',UpperCAmelCase__       )

   # Prediction
   if training_args.do_predict:
      logger.info('*** Predict ***'       )
      a__  					=		trainer.predict(UpperCAmelCase__,metric_key_prefix='predict'       )

      a__  					=		(
          data_args.max_predict_samples if data_args.max_predict_samples is not None else len(UpperCAmelCase__       )
      )
      a__  					=		min(UpperCAmelCase__,len(UpperCAmelCase__       )       )

      trainer.log_metrics('predict',UpperCAmelCase__       )
      trainer.save_metrics('predict',UpperCAmelCase__       )

      a__  					=		np.argmax(UpperCAmelCase__,axis=1       )
      a__  					=		os.path.join(training_args.output_dir,'predictions.txt'       )
      if trainer.is_world_process_zero():
         with open(UpperCAmelCase__,'w'       ) as writer:
            writer.write('index\tprediction\n'       )
            for index, item in enumerate(UpperCAmelCase__       ):
               a__  					=		label_list[item]
               writer.write(f'''{index}\t{item}\n'''       )


if __name__ == "__main__":
     main()





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


_lowerCAmelCase  :      List[str]			 =get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
_lowerCAmelCase  :      List[str]			 =get_tests_dir("""fixtures/vocab.json""")
_lowerCAmelCase  :      Dict			 =get_tests_dir("""fixtures""")

class __UpperCamelCase     (				unittest.TestCase		):






					'''simple docstring'''



					__magic_name__        =   ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]





					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Union[str, Any]									= 0





					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Optional[int]									= AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"						)
						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmpdirname:
							UpperCAmelCase__:	Any									= WavaVecaConfig()
							UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained("facebook/wav2vec2-base-960h"						)

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

							UpperCAmelCase__:	int									= AutoProcessor.from_pretrained(lowerCamelCase__						)

						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmpdirname:
							# copy relevant files
							copyfile(lowerCamelCase__				,      os.path.join(lowerCamelCase__				,      lowerCamelCase__						)						)
							copyfile(lowerCamelCase__				,      os.path.join(lowerCamelCase__				,      "vocab.json"						)						)

							UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained(lowerCamelCase__						)

						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmpdirname:
							UpperCAmelCase__:	Optional[Any]									= WavaVecaFeatureExtractor()
							UpperCAmelCase__:	List[Any]									= AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"						)

							UpperCAmelCase__:	Dict									= WavaVecaProcessor(lowerCamelCase__				,      lowerCamelCase__						)

							# save in new folder
							processor.save_pretrained(lowerCamelCase__						)

							# drop `processor_class` in tokenizer
							with open(os.path.join(lowerCamelCase__				,      lowerCamelCase__						)				,      "r"						) as f:
								UpperCAmelCase__:	Optional[int]									= json.load(lowerCamelCase__						)
								config_dict.pop("processor_class"						)

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

							UpperCAmelCase__:	Any									= AutoProcessor.from_pretrained(lowerCamelCase__						)

						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmpdirname:
							UpperCAmelCase__:	str									= WavaVecaFeatureExtractor()
							UpperCAmelCase__:	Tuple									= AutoTokenizer.from_pretrained("facebook/wav2vec2-base-960h"						)

							UpperCAmelCase__:	List[Any]									= WavaVecaProcessor(lowerCamelCase__				,      lowerCamelCase__						)

							# save in new folder
							processor.save_pretrained(lowerCamelCase__						)

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

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

							UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained(lowerCamelCase__						)

						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						with tempfile.TemporaryDirectory() as tmpdirname:
							UpperCAmelCase__:	Union[str, Any]									= WavaVecaConfig(processor_class="Wav2Vec2Processor"						)
							model_config.save_pretrained(lowerCamelCase__						)
							# copy relevant files
							copyfile(lowerCamelCase__				,      os.path.join(lowerCamelCase__				,      "vocab.json"						)						)
							# create emtpy sample processor
							with open(os.path.join(lowerCamelCase__				,      lowerCamelCase__						)				,      "w"						) as f:
								f.write("{}"						)

							UpperCAmelCase__:	Union[str, Any]									= AutoProcessor.from_pretrained(lowerCamelCase__						)

						self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)





					def    _UpperCAmelCase    (				self						):
						# If remote code is not set, we will time out when asking whether to load the model.
						with self.assertRaises(lowerCamelCase__						):
							UpperCAmelCase__:	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(lowerCamelCase__						):
							UpperCAmelCase__:	Optional[int]									= AutoProcessor.from_pretrained(
							    "hf-internal-testing/test_dynamic_processor"				,      trust_remote_code=lowerCamelCase__						)

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

						UpperCAmelCase__:	Dict									= processor.feature_extractor
						self.assertTrue(feature_extractor.special_attribute_present						)
						self.assertEqual(feature_extractor.__class__.__name__				,      "NewFeatureExtractor"						)

						UpperCAmelCase__:	Any									= 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
							UpperCAmelCase__:	Dict									= AutoProcessor.from_pretrained(
							    "hf-internal-testing/test_dynamic_processor"				,      trust_remote_code=lowerCamelCase__				,      use_fast=lowerCamelCase__						)
							UpperCAmelCase__:	str									= 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    _UpperCAmelCase    (				self						):
						try:
							AutoConfig.register("custom"				,      lowerCamelCase__						)
							AutoFeatureExtractor.register(lowerCamelCase__				,      lowerCamelCase__						)
							AutoTokenizer.register(lowerCamelCase__				,      slow_tokenizer_class=lowerCamelCase__						)
							AutoProcessor.register(lowerCamelCase__				,      lowerCamelCase__						)
							# Trying to register something existing in the Transformers library will raise an error
							with self.assertRaises(lowerCamelCase__						):
								AutoProcessor.register(lowerCamelCase__				,      lowerCamelCase__						)

							# Now that the config is registered, it can be used as any other config with the auto-API
							UpperCAmelCase__:	Dict									= CustomFeatureExtractor.from_pretrained(lowerCamelCase__						)

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

							UpperCAmelCase__:	Optional[int]									= CustomProcessor(lowerCamelCase__				,      lowerCamelCase__						)

							with tempfile.TemporaryDirectory() as tmp_dir:
								processor.save_pretrained(lowerCamelCase__						)
								UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained(lowerCamelCase__						)
								self.assertIsInstance(lowerCamelCase__				,      lowerCamelCase__						)

						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    _UpperCAmelCase    (				self						):

						class __UpperCamelCase     (				_a		):






											'''simple docstring'''



											__magic_name__        =   False

						class __UpperCamelCase     (				_a		):






											'''simple docstring'''



											__magic_name__        =   False

						class __UpperCamelCase     (				_a		):






											'''simple docstring'''



											__magic_name__        =   "AutoFeatureExtractor"
											__magic_name__        =   "AutoTokenizer"
											__magic_name__        =   False

						try:
							AutoConfig.register("custom"				,      lowerCamelCase__						)
							AutoFeatureExtractor.register(lowerCamelCase__				,      lowerCamelCase__						)
							AutoTokenizer.register(lowerCamelCase__				,      slow_tokenizer_class=lowerCamelCase__						)
							AutoProcessor.register(lowerCamelCase__				,      lowerCamelCase__						)
							# If remote code is not set, the default is to use local classes.
							UpperCAmelCase__:	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.
							UpperCAmelCase__:	Union[str, Any]									= AutoProcessor.from_pretrained(
							    "hf-internal-testing/test_dynamic_processor"				,      trust_remote_code=lowerCamelCase__						)
							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.
							UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained(
							    "hf-internal-testing/test_dynamic_processor"				,      trust_remote_code=lowerCamelCase__						)
							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    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Union[str, Any]									= AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-bert"						)
						self.assertEqual(processor.__class__.__name__				,      "BertTokenizerFast"						)





					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Tuple									= AutoProcessor.from_pretrained("hf-internal-testing/tiny-random-convnext"						)
						self.assertEqual(processor.__class__.__name__				,      "ConvNextImageProcessor"						)

@is_staging_test
class __UpperCamelCase     (				unittest.TestCase		):






					'''simple docstring'''



					__magic_name__        =   ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"]





					@classmethod
					def    _UpperCAmelCase    (				cls						):
						UpperCAmelCase__:	Dict									= TOKEN
						HfFolder.save_token(lowerCamelCase__						)





					@classmethod
					def    _UpperCAmelCase    (				cls						):
						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    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Optional[Any]									= WavaVecaProcessor.from_pretrained(lowerCamelCase__						)
						with tempfile.TemporaryDirectory() as tmp_dir:
							processor.save_pretrained(
							    os.path.join(lowerCamelCase__				,      "test-processor"						)				,      push_to_hub=lowerCamelCase__				,      use_auth_token=self._token						)

							UpperCAmelCase__:	Union[str, Any]									= WavaVecaProcessor.from_pretrained(F"{USER}/test-processor"						)
							for k, v in processor.feature_extractor.__dict__.items():
								self.assertEqual(lowerCamelCase__				,      getattr(new_processor.feature_extractor				,      lowerCamelCase__						)						)
							self.assertDictEqual(new_processor.tokenizer.get_vocab()				,      processor.tokenizer.get_vocab()						)





					def    _UpperCAmelCase    (				self						):
						UpperCAmelCase__:	Dict									= WavaVecaProcessor.from_pretrained(lowerCamelCase__						)

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

							UpperCAmelCase__:	Optional[int]									= WavaVecaProcessor.from_pretrained("valid_org/test-processor-org"						)
							for k, v in processor.feature_extractor.__dict__.items():
								self.assertEqual(lowerCamelCase__				,      getattr(new_processor.feature_extractor				,      lowerCamelCase__						)						)
							self.assertDictEqual(new_processor.tokenizer.get_vocab()				,      processor.tokenizer.get_vocab()						)





					def    _UpperCAmelCase    (				self						):
						CustomFeatureExtractor.register_for_auto_class()
						CustomTokenizer.register_for_auto_class()
						CustomProcessor.register_for_auto_class()

						UpperCAmelCase__:	List[str]									= CustomFeatureExtractor.from_pretrained(lowerCamelCase__						)

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

						UpperCAmelCase__:	str									= CustomProcessor(lowerCamelCase__				,      lowerCamelCase__						)

						with tempfile.TemporaryDirectory() as tmp_dir:
							create_repo(F"{USER}/test-dynamic-processor"				,      token=self._token						)
							UpperCAmelCase__:	int									= Repository(lowerCamelCase__				,      clone_from=F"{USER}/test-dynamic-processor"				,      token=self._token						)
							processor.save_pretrained(lowerCamelCase__						)

							# 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(lowerCamelCase__				,      "tokenizer_config.json"						)						) as f:
								UpperCAmelCase__:	Tuple									= json.load(lowerCamelCase__						)
							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(lowerCamelCase__				,      "custom_feature_extraction.py"						)						)						)
							self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,      "custom_tokenization.py"						)						)						)
							self.assertTrue(os.path.isfile(os.path.join(lowerCamelCase__				,      "custom_processing.py"						)						)						)

							repo.push_to_hub()

						UpperCAmelCase__:	Union[str, Any]									= AutoProcessor.from_pretrained(F"{USER}/test-dynamic-processor"				,      trust_remote_code=lowerCamelCase__						)
						# 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"						)