
'''simple docstring'''




import argparse

import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


lowercase			:				Optional[int]    		=			16
lowercase			:				Optional[Any]    		=			32







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__ = 16						):




    '''simple docstring'''



    A       :   int					=						AutoTokenizer.from_pretrained('''bert-base-cased'''						)
    A       :   Optional[Any]					=						load_dataset('''glue'''		,				'''mrpc'''						)

    def tokenize_function(snake_case__						):
        # max_length=None => use the model max length (it's actually the default)
        A       :   Tuple					=						tokenizer(examples['''sentence1''']		,				examples['''sentence2''']		,				truncation=snake_case__		,				max_length=snake_case__						)
        return outputs

    # Apply the method we just defined to all the examples in all the splits of the dataset
    # starting with the main process first:
    with accelerator.main_process_first():
        A       :   Optional[int]					=						datasets.map(
            snake_case__		,				batched=snake_case__		,				remove_columns=['''idx''', '''sentence1''', '''sentence2''']		,				)

    # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
    # transformers library
    A       :   Dict					=						tokenized_datasets.rename_column('''label'''		,				'''labels'''						)

    def collate_fn(snake_case__						):
        # On TPU it's best to pad everything to the same length or training will be very slow.
        A       :   Tuple					=						128 if accelerator.distributed_type == DistributedType.TPU else None
        # When using mixed precision we want round multiples of 8/16
        if accelerator.mixed_precision == "fp8":
            A       :   List[Any]					=						16
        elif accelerator.mixed_precision != "no":
            A       :   Dict					=						8
        else:
            A       :   Tuple					=						None

        return tokenizer.pad(
            snake_case__		,				padding='''longest'''		,				max_length=snake_case__		,				pad_to_multiple_of=snake_case__		,				return_tensors='''pt'''		,				)

    # Instantiate dataloaders.
    A       :   Optional[int]					=						DataLoader(
        tokenized_datasets['''train''']		,				shuffle=snake_case__		,				collate_fn=snake_case__		,				batch_size=snake_case__		,				drop_last=snake_case__						)
    A       :   int					=						DataLoader(
        tokenized_datasets['''validation''']		,				shuffle=snake_case__		,				collate_fn=snake_case__		,				batch_size=snake_case__		,				drop_last=(accelerator.mixed_precision == '''fp8''')		,				)

    return train_dataloader, eval_dataloader







def 		lowerCAmelCase_				(   snake_case__		,				snake_case__						):




    '''simple docstring'''



    A       :   Dict					=						Accelerator(cpu=args.cpu		,				mixed_precision=args.mixed_precision						)
    # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
    A       :   Optional[Any]					=						config['''lr''']
    A       :   Dict					=						int(config['''num_epochs''']						)
    A       :   List[str]					=						int(config['''seed''']						)
    A       :   Optional[int]					=						int(config['''batch_size''']						)

    A       :   Tuple					=						evaluate.load('''glue'''		,				'''mrpc'''						)

    # If the batch size is too big we use gradient accumulation
    A       :   List[str]					=						1
    if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
        A       :   str					=						batch_size // MAX_GPU_BATCH_SIZE
        A       :   int					=						MAX_GPU_BATCH_SIZE

    set_seed(snake_case__						)
    A,  A       :   Optional[Any]					=						get_dataloaders(snake_case__		,				snake_case__						)
    # Instantiate the model (we build the model here so that the seed also control new weights initialization)
    A       :   List[str]					=						AutoModelForSequenceClassification.from_pretrained('''bert-base-cased'''		,				return_dict=snake_case__						)

    # We could avoid this line since the accelerator is set with `device_placement=True` (default value).
    # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
    # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
    A       :   int					=						model.to(accelerator.device						)
    # Instantiate optimizer
    A       :   List[Any]					=						AdamW(params=model.parameters()		,				lr=snake_case__						)

    # Instantiate scheduler
    A       :   Any					=						get_linear_schedule_with_warmup(
        optimizer=snake_case__		,				num_warmup_steps=100		,				num_training_steps=(len(snake_case__						) * num_epochs) // gradient_accumulation_steps		,				)

    # Prepare everything
    # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
    # prepare method.

    A,  A,  A,  A,  A       :   Tuple					=						accelerator.prepare(
        snake_case__		,				snake_case__		,				snake_case__		,				snake_case__		,				snake_case__						)

    # Now we train the model
    for epoch in range(snake_case__						):
        model.train()
        for step, batch in enumerate(snake_case__						):
            # We could avoid this line since we set the accelerator with `device_placement=True`.
            batch.to(accelerator.device						)
            A       :   Optional[Any]					=						model(**snake_case__						)
            A       :   Optional[Any]					=						outputs.loss
            A       :   Dict					=						loss / gradient_accumulation_steps
            accelerator.backward(snake_case__						)
            if step % gradient_accumulation_steps == 0:
                optimizer.step()
                lr_scheduler.step()
                optimizer.zero_grad()

        model.eval()
        for step, batch in enumerate(snake_case__						):
            # We could avoid this line since we set the accelerator with `device_placement=True`.
            batch.to(accelerator.device						)
            with torch.no_grad():
                A       :   str					=						model(**snake_case__						)
            A       :   str					=						outputs.logits.argmax(dim=-1						)
            A,  A       :   List[str]					=						accelerator.gather_for_metrics((predictions, batch['''labels'''])						)
            metric.add_batch(
                predictions=snake_case__		,				references=snake_case__		,				)

        A       :   Optional[Any]					=						metric.compute()
        # Use accelerator.print to print only on the main process.
        accelerator.print(F'epoch {epoch}:'		,				snake_case__						)







def 		lowerCAmelCase_				(   ):




    '''simple docstring'''



    A       :   str					=						argparse.ArgumentParser(description='''Simple example of training script.'''						)
    parser.add_argument(
        '''--mixed_precision'''		,				type=snake_case__		,				default=snake_case__		,				choices=['''no''', '''fp16''', '''bf16''', '''fp8''']		,				help='''Whether to use mixed precision. Choose'''
        '''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
        '''and an Nvidia Ampere GPU.'''		,				)
    parser.add_argument('''--cpu'''		,				action='''store_true'''		,				help='''If passed, will train on the CPU.'''						)
    A       :   int					=						parser.parse_args()
    A       :   Union[str, Any]					=						{'''lr''': 2E-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
    training_function(snake_case__		,				snake_case__						)


if __name__ == "__main__":
      main()






'''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'''	)




