





"""simple docstring"""



from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import tensorflow as tf

       from transformers.models.xglm.modeling_tf_xglm import (
           TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFXGLMForCausalLM,
           TFXGLMModel,
       )






@require_tf
class 						__snake_case   :





 """simple docstring"""


 _lowerCamelCase								=	XGLMConfig
 _lowerCamelCase								=	{}
 _lowerCamelCase								=	"""gelu"""

 def __init__(       self   ,		__lowerCamelCase   ,		__lowerCamelCase=14   ,		__lowerCamelCase=7   ,		__lowerCamelCase=True   ,		__lowerCamelCase=True   ,		__lowerCamelCase=True   ,		__lowerCamelCase=99   ,		__lowerCamelCase=32   ,		__lowerCamelCase=2   ,		__lowerCamelCase=4   ,		__lowerCamelCase=37   ,		__lowerCamelCase="gelu"   ,		__lowerCamelCase=0.1   ,		__lowerCamelCase=0.1   ,		__lowerCamelCase=512   ,		__lowerCamelCase=0.0_2   ,		):



     '''simple docstring'''




     __A       :		str							=	parent
     __A       :		Dict							=	batch_size
     __A       :		Optional[Any]							=	seq_length
     __A       :		Any							=	is_training
     __A       :		List[Any]							=	use_input_mask
     __A       :		Any							=	use_labels
     __A       :		int							=	vocab_size
     __A       :		int							=	d_model
     __A       :		Tuple							=	num_hidden_layers
     __A       :		Dict							=	num_attention_heads
     __A       :		str							=	ffn_dim
     __A       :		List[Any]							=	activation_function
     __A       :		Tuple							=	activation_dropout
     __A       :		Tuple							=	attention_dropout
     __A       :		Optional[int]							=	max_position_embeddings
     __A       :		Union[str, Any]							=	initializer_range
     __A       :		int							=	None
     __A       :		Dict							=	0
     __A       :		Dict							=	2
     __A       :		str							=	1

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return XGLMConfig.from_pretrained('''facebook/xglm-564M'''    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[Any]							=	tf.clip_by_value(
         ids_tensor([self.batch_size, self.seq_length]   ,		self.vocab_size    )   ,		clip_value_min=0   ,		clip_value_max=3    )

     __A       :		int							=	None
     if self.use_input_mask:
         __A       :		Union[str, Any]							=	random_attention_mask([self.batch_size, self.seq_length]    )

     __A       :		List[Any]							=	self.get_config()

     __A       :		Optional[Any]							=	floats_tensor([self.num_hidden_layers, self.num_attention_heads]   ,		2    )

     return (
         config,
         input_ids,
         input_mask,
         head_mask,
     )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     return XGLMConfig(
         vocab_size=self.vocab_size   ,		d_model=self.hidden_size   ,		num_layers=self.num_hidden_layers   ,		attention_heads=self.num_attention_heads   ,		ffn_dim=self.ffn_dim   ,		activation_function=self.activation_function   ,		activation_dropout=self.activation_dropout   ,		attention_dropout=self.attention_dropout   ,		max_position_embeddings=self.max_position_embeddings   ,		initializer_range=self.initializer_range   ,		use_cache=__lowerCamelCase   ,		bos_token_id=self.bos_token_id   ,		eos_token_id=self.eos_token_id   ,		pad_token_id=self.pad_token_id   ,		return_dict=__lowerCamelCase   ,		)







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Tuple							=	self.prepare_config_and_inputs()

     (
         (
         __A
     )					,			(
         __A
     )					,			(
         __A
     )					,			(
         __A
     )					,			
     )       :		str							=	config_and_inputs

     __A       :		Dict							=	{
         '''input_ids''': input_ids,
         '''head_mask''': head_mask,
     }

     return config, inputs_dict






@require_tf
class 						__snake_case   (						SCREAMING_SNAKE_CASE__				,				SCREAMING_SNAKE_CASE__				,				unittest.TestCase	):





 """simple docstring"""


 _lowerCamelCase								=	(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
 _lowerCamelCase								=	(TFXGLMForCausalLM,) if is_tf_available() else ()
 _lowerCamelCase								=	(
     {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {}
 )
 _lowerCamelCase								=	False
 _lowerCamelCase								=	False
 _lowerCamelCase								=	False

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	TFXGLMModelTester(self    )
     __A       :		Any							=	ConfigTester(self   ,		config_class=__lowerCamelCase   ,		n_embd=37    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     self.config_tester.run_common_tests()

 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         __A       :		Any							=	TFXGLMModel.from_pretrained(__lowerCamelCase    )
         self.assertIsNotNone(__lowerCamelCase    )







 @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''    )
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     super().test_resize_token_embeddings()






@require_tf
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


 @slow
 def    UpperCamelCase__(       self   ,		__lowerCamelCase=True    ):



     '''simple docstring'''




     __A       :		Any							=	TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )
     __A       :		Optional[int]							=	tf.convert_to_tensor([[2, 268, 9865]]   ,		dtype=tf.intaa    )  # The dog
     # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
     # fmt: off
     __A       :		Dict							=	[2, 268, 9865, 67, 11, 1988, 5_7252, 9865, 5, 984, 67, 1988, 21_3838, 1658, 53, 7_0446, 33, 6657, 278, 1581]
     # fmt: on
     __A       :		int							=	model.generate(__lowerCamelCase   ,		do_sample=__lowerCamelCase   ,		num_beams=1    )
     if verify_outputs:
         self.assertListEqual(output_ids[0].numpy().tolist()   ,		__lowerCamelCase    )

 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''    )
     __A       :		List[str]							=	TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )

     tf.random.set_seed(0    )
     __A       :		str							=	tokenizer('''Today is a nice day and'''   ,		return_tensors='''tf'''    )
     __A       :		Union[str, Any]							=	tokenized.input_ids
     # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
     with tf.device(''':/CPU:0'''    ):
         __A       :		Dict							=	model.generate(__lowerCamelCase   ,		do_sample=__lowerCamelCase   ,		seed=[7, 0]    )
     __A       :		str							=	tokenizer.decode(output_ids[0]   ,		skip_special_tokens=__lowerCamelCase    )

     __A       :		Any							=	(
         '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
     )
     self.assertEqual(__lowerCamelCase   ,		__lowerCamelCase    )







 @slow
 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Union[str, Any]							=	TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''    )
     __A       :		int							=	XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''    )

     __A       :		List[str]							=	'''left'''

     # use different length sentences to test batching
     __A       :		Tuple							=	[
         '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
         '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
         '''regardless of whether left padding is applied or not. When''',
         '''Hello, my dog is a little''',
     ]

     __A       :		str							=	tokenizer(__lowerCamelCase   ,		return_tensors='''tf'''   ,		padding=__lowerCamelCase    )
     __A       :		Optional[Any]							=	inputs['''input_ids''']

     __A       :		Optional[Any]							=	model.generate(input_ids=__lowerCamelCase   ,		attention_mask=inputs['''attention_mask''']   ,		max_new_tokens=12    )

     __A       :		int							=	tokenizer(sentences[0]   ,		return_tensors='''tf'''    ).input_ids
     __A       :		Dict							=	model.generate(input_ids=__lowerCamelCase   ,		max_new_tokens=12    )

     __A       :		str							=	tokenizer(sentences[1]   ,		return_tensors='''tf'''    ).input_ids
     __A       :		Dict							=	model.generate(input_ids=__lowerCamelCase   ,		max_new_tokens=12    )

     __A       :		int							=	tokenizer.batch_decode(__lowerCamelCase   ,		skip_special_tokens=__lowerCamelCase    )
     __A       :		List[str]							=	tokenizer.decode(output_non_padded[0]   ,		skip_special_tokens=__lowerCamelCase    )
     __A       :		str							=	tokenizer.decode(output_padded[0]   ,		skip_special_tokens=__lowerCamelCase    )

     __A       :		Any							=	[
         '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
         '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
         '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '''
         '''a single''',
         '''Hello, my dog is a little bit of a shy one, but he is very friendly''',
     ]
     self.assertListEqual(__lowerCamelCase   ,		__lowerCamelCase    )
     self.assertListEqual(__lowerCamelCase   ,		[non_padded_sentence, padded_sentence]    )











"""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


a_					=     get_tests_dir("""fixtures/dummy_feature_extractor_config.json""")
a_					=     get_tests_dir("""fixtures/vocab.json""")
a_					=     get_tests_dir("""fixtures""")






class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


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

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		Optional[Any]							=	0

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     __A       :		str							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )
     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		str							=	WavaVecaConfig()
         __A       :		Dict							=	AutoProcessor.from_pretrained('''facebook/wav2vec2-base-960h'''    )

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

         __A       :		List[str]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Union[str, Any]							=	WavaVecaFeatureExtractor()
         __A       :		Optional[Any]							=	AutoTokenizer.from_pretrained('''facebook/wav2vec2-base-960h'''    )

         __A       :		Union[str, Any]							=	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:
             __A       :		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    )    )

         __A       :		Tuple							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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

         __A       :		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:
             __A       :		int							=	json.load(__lowerCamelCase    )
             config_dict.pop('''processor_class'''    )

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

         __A       :		Optional[int]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with tempfile.TemporaryDirectory() as tmpdirname:
         __A       :		Optional[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('''{}'''    )

         __A       :		Union[str, Any]							=	AutoProcessor.from_pretrained(__lowerCamelCase    )

     self.assertIsInstance(__lowerCamelCase   ,		__lowerCamelCase    )

 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




     with self.assertRaises(__lowerCamelCase    ):
         __A       :		Union[str, 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    ):
         __A       :		Dict							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase    )

     __A       :		List[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'''    )

     __A       :		Union[str, Any]							=	processor.feature_extractor
     self.assertTrue(feature_extractor.special_attribute_present    )
     self.assertEqual(feature_extractor.__class__.__name__   ,		'''NewFeatureExtractor'''    )

     __A       :		Optional[int]							=	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       :		int							=	AutoProcessor.from_pretrained(
             '''hf-internal-testing/test_dynamic_processor'''   ,		trust_remote_code=__lowerCamelCase   ,		use_fast=__lowerCamelCase    )
         __A       :		Optional[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    UpperCamelCase__(       self    ):



     '''simple docstring'''




     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
         __A       :		str							=	CustomFeatureExtractor.from_pretrained(__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmp_dir:
             __A       :		Optional[Any]							=	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]    )    )
             __A       :		Dict							=	CustomTokenizer(__lowerCamelCase    )

         __A       :		Optional[Any]							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

         with tempfile.TemporaryDirectory() as tmp_dir:
             processor.save_pretrained(__lowerCamelCase    )
             __A       :		List[str]							=	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    ):



     '''simple docstring'''




     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	False






     class 						__snake_case   (						SCREAMING_SNAKE_CASE__	):





      """simple docstring"""


      _lowerCamelCase								=	"""AutoFeatureExtractor"""
      _lowerCamelCase								=	"""AutoTokenizer"""
      _lowerCamelCase								=	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.
         __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       :		int							=	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.
         __A       :		str							=	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    ):



     '''simple docstring'''




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







 def    UpperCamelCase__(       self    ):



     '''simple docstring'''




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






@is_staging_test
class 						__snake_case   (						unittest.TestCase	):





 """simple docstring"""


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

 @classmethod
 def    UpperCamelCase__(       cls    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	TOKEN
     HfFolder.save_token(__lowerCamelCase    )

 @classmethod
 def    UpperCamelCase__(       cls    ):



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



     '''simple docstring'''




     __A       :		Tuple							=	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    )

         __A       :		Tuple							=	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    ):



     '''simple docstring'''




     __A       :		Optional[int]							=	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'''   ,		)

         __A       :		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    ):



     '''simple docstring'''




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

     __A       :		Any							=	CustomFeatureExtractor.from_pretrained(__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         __A       :		List[Any]							=	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]    )    )
         __A       :		Optional[int]							=	CustomTokenizer(__lowerCamelCase    )

     __A       :		Any							=	CustomProcessor(__lowerCamelCase   ,		__lowerCamelCase    )

     with tempfile.TemporaryDirectory() as tmp_dir:
         create_repo(F"""{USER}/test-dynamic-processor"""   ,		token=self._token    )
         __A       :		Tuple							=	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:
             __A       :		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()

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




