
'''simple docstring'''







import argparse
import gc
import json
import os
import re

import torch
from huggingface_hub import hf_hub_download

from transformers import AutoModelForCausalLM, AutoTokenizer, PreTrainedTokenizerFast, RwkvConfig
from transformers.modeling_utils import WEIGHTS_INDEX_NAME, shard_checkpoint


_lowercase :  Optional[int]    							=       {
    '169M': 1_2,
    '430M': 2_4,
    '1B5': 2_4,
    '3B': 3_2,
    '7B': 3_2,
    '14B': 4_0,
}

_lowercase :  Optional[Any]    							=       {
    '169M': 7_6_8,
    '430M': 1_0_2_4,
    '1B5': 2_0_4_8,
    '3B': 2_5_6_0,
    '7B': 4_0_9_6,
    '14B': 5_1_2_0,
}
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: str							):



						"""simple docstring"""





						lowercase_	:     Optional[Any]													=       list(state_dict.keys()							)
						for name in state_dict_keys:
												lowercase_	:     str													=       state_dict.pop(snake_case__							)
												# emb -> embedding
												if name.startswith('''emb.'''							):
																		lowercase_	:     Optional[Any]													=       name.replace('''emb.'''      ,      '''embeddings.'''							)
												# ln_0 -> pre_ln (only present at block 0)
												if name.startswith('''blocks.0.ln0'''							):
																		lowercase_	:     Union[str, Any]													=       name.replace('''blocks.0.ln0'''      ,      '''blocks.0.pre_ln'''							)
												# att -> attention
												lowercase_	:     int													=       re.sub(R'''blocks\.(\d+)\.att'''      ,      R'''blocks.\1.attention'''      ,      snake_case__							)
												# ffn -> feed_forward
												lowercase_	:     List[Any]													=       re.sub(R'''blocks\.(\d+)\.ffn'''      ,      R'''blocks.\1.feed_forward'''      ,      snake_case__							)
												# time_mix_k -> time_mix_key and reshape
												if name.endswith('''.time_mix_k'''							):
																		lowercase_	:     List[str]													=       name.replace('''.time_mix_k'''      ,      '''.time_mix_key'''							)
												# time_mix_v -> time_mix_value and reshape
												if name.endswith('''.time_mix_v'''							):
																		lowercase_	:     Union[str, Any]													=       name.replace('''.time_mix_v'''      ,      '''.time_mix_value'''							)
												# time_mix_r -> time_mix_key and reshape
												if name.endswith('''.time_mix_r'''							):
																		lowercase_	:     Union[str, Any]													=       name.replace('''.time_mix_r'''      ,      '''.time_mix_receptance'''							)

												if name != "head.weight":
																		lowercase_	:     List[Any]													=       '''rwkv.''' + name

												lowercase_	:     Dict													=       weight
						return state_dict
def 					snake_case_		(				__SCREAMING_SNAKE_CASE					: List[str]      ,      __SCREAMING_SNAKE_CASE					: Any      ,      __SCREAMING_SNAKE_CASE					: List[str]      ,      __SCREAMING_SNAKE_CASE					: Union[str, Any]=None      ,      __SCREAMING_SNAKE_CASE					: Dict=None      ,      __SCREAMING_SNAKE_CASE					: Any=False      ,      __SCREAMING_SNAKE_CASE					: int=None							):



						"""simple docstring"""





						if tokenizer_file is None:
												print('''No `--tokenizer_file` provided, we will use the default tokenizer.'''							)
												lowercase_	:     int													=       50277
												lowercase_	:     Optional[int]													=       AutoTokenizer.from_pretrained('''EleutherAI/gpt-neox-20b'''							)
						else:
												lowercase_	:     str													=       PreTrainedTokenizerFast(tokenizer_file=snake_case__							)
												lowercase_	:     Any													=       len(snake_case__							)
						tokenizer.save_pretrained(snake_case__							)

						# 2. Build the config
						lowercase_	:     List[str]													=       list(NUM_HIDDEN_LAYERS_MAPPING.keys()							)
						if size is None:
												# Try to infer size from the checkpoint name
												for candidate in possible_sizes:
																		if candidate in checkpoint_file:
																								lowercase_	:     List[str]													=       candidate
																								break
												if size is None:
																		raise ValueError('''Could not infer the size, please provide it with the `--size` argument.'''							)
						if size not in possible_sizes:
												raise ValueError(F'''`size` should be one of {possible_sizes}, got {size}.'''							)

						lowercase_	:     Any													=       RwkvConfig(
						    vocab_size=snake_case__      ,      num_hidden_layers=NUM_HIDDEN_LAYERS_MAPPING[size]      ,      hidden_size=HIDEN_SIZE_MAPPING[size]      ,      )
						config.save_pretrained(snake_case__							)

						# 3. Download model file then convert state_dict
						lowercase_	:     Union[str, Any]													=       hf_hub_download(snake_case__      ,      snake_case__							)
						lowercase_	:     Tuple													=       torch.load(snake_case__      ,      map_location='''cpu'''							)
						lowercase_	:     List[Any]													=       convert_state_dict(snake_case__							)

						# 4. Split in shards and save
						lowercase_	:     List[str]													=       shard_checkpoint(snake_case__							)
						for shard_file, shard in shards.items():
												torch.save(snake_case__      ,      os.path.join(snake_case__      ,      snake_case__							)							)

						if index is not None:
												lowercase_	:     Dict													=       os.path.join(snake_case__      ,      snake_case__							)
												# Save the index as well
												with open(snake_case__      ,      '''w'''      ,      encoding='''utf-8'''							) as f:
																		lowercase_	:     List[Any]													=       json.dumps(snake_case__      ,      indent=2      ,      sort_keys=snake_case__							) + '''\n'''
																		f.write(snake_case__							)

												# 5. Clean up shards (for some reason the file PyTorch saves take the same space as the whole state_dict
												print(
												    '''Cleaning up shards. This may error with an OOM error, it this is the case don\'t worry you still have converted the model.'''							)
												lowercase_	:     List[Any]													=       list(shards.keys()							)

												del state_dict
												del shards
												gc.collect()

												for shard_file in shard_files:
																		lowercase_	:     Union[str, Any]													=       torch.load(os.path.join(snake_case__      ,      snake_case__							)							)
																		torch.save({k: v.cpu().clone() for k, v in state_dict.items()}      ,      os.path.join(snake_case__      ,      snake_case__							)							)

						del state_dict
						gc.collect()

						if push_to_hub:
												if model_name is None:
																		raise ValueError('''Please provide a `model_name` to push the model to the Hub.'''							)
												lowercase_	:     int													=       AutoModelForCausalLM.from_pretrained(snake_case__							)
												model.push_to_hub(snake_case__      ,      max_shard_size='''2GB'''							)
												tokenizer.push_to_hub(snake_case__							)


if __name__ == "__main__":
							_lowercase :  List[str]    							=       argparse.ArgumentParser()
							# Required parameters
							parser.add_argument(
							    "--repo_id", default=None, type=str, required=True, help="Repo ID from which to pull the checkpoint."
							)
							parser.add_argument(
							    "--checkpoint_file", default=None, type=str, required=True, help="Name of the checkpoint file in the repo."
							)
							parser.add_argument(
							    "--output_dir", default=None, type=str, required=True, help="Where to save the converted model."
							)
							parser.add_argument(
							    "--tokenizer_file",
							    default=None,
							    type=str,
							    help="Path to the tokenizer file to use (if not provided, only the model is converted).",
							)
							parser.add_argument(
							    "--size",
							    default=None,
							    type=str,
							    help="Size of the model. Will be inferred from the `checkpoint_file` if not passed.",
							)
							parser.add_argument(
							    "--push_to_hub",
							    action="store_true",
							    help="Push to the Hub the converted model.",
							)
							parser.add_argument(
							    "--model_name",
							    default=None,
							    type=str,
							    help="Name of the pushed model on the Hub, including the username / organization.",
							)

							_lowercase :  Union[str, Any]    							=       parser.parse_args()
							convert_rmkv_checkpoint_to_hf_format(
							    args.repo_id,
							    args.checkpoint_file,
							    args.output_dir,
							    size=args.size,
							    tokenizer_file=args.tokenizer_file,
							    push_to_hub=args.push_to_hub,
							    model_name=args.model_name,
							)





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




