'''simple docstring'''






import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()





class        A__				(			SCREAMING_SNAKE_CASE__   ,						unittest.TestCase  ):





   """simple docstring"""





   UpperCamelCase_			:		Optional[Any]       							=	KandinskyVaaPipeline
   UpperCamelCase_			:		Union[str, Any]       							=	[
       '''image_embeds''',
       '''negative_image_embeds''',
   ]
   UpperCamelCase_			:		Optional[int]       							=	['''image_embeds''', '''negative_image_embeds''']
   UpperCamelCase_			:		Any       							=	[
       '''generator''',
       '''height''',
       '''width''',
       '''latents''',
       '''guidance_scale''',
       '''num_inference_steps''',
       '''return_dict''',
       '''guidance_scale''',
       '''num_images_per_prompt''',
       '''output_type''',
       '''return_dict''',
   ]
   UpperCamelCase_			:		Tuple       							=	False




   @property
   def      _lowerCAmelCase						(					self	:						Optional[int]     )			->       List[Any]:







      """simple docstring"""




      return 3_2




   @property
   def      _lowerCAmelCase						(					self	:						Any     )			->       List[str]:







      """simple docstring"""




      return 3_2




   @property
   def      _lowerCAmelCase						(					self	:						Optional[Any]     )			->       Dict:







      """simple docstring"""




      return self.time_input_dim




   @property
   def      _lowerCAmelCase						(					self	:						str     )			->       Union[str, Any]:







      """simple docstring"""




      return self.time_input_dim * 4




   @property
   def      _lowerCAmelCase						(					self	:						Optional[Any]     )			->       Any:







      """simple docstring"""




      return 1_0_0




   @property
   def      _lowerCAmelCase						(					self	:						List[str]     )			->       Optional[Any]:







      """simple docstring"""




      torch.manual_seed(0     )

      _UpperCAmelCase				:      Optional[Any]				=  {
          '''in_channels''': 4,
          # Out channels is double in channels because predicts mean and variance
          '''out_channels''': 8,
          '''addition_embed_type''': '''image''',
          '''down_block_types''': ('''ResnetDownsampleBlock2D''', '''SimpleCrossAttnDownBlock2D'''),
          '''up_block_types''': ('''SimpleCrossAttnUpBlock2D''', '''ResnetUpsampleBlock2D'''),
          '''mid_block_type''': '''UNetMidBlock2DSimpleCrossAttn''',
          '''block_out_channels''': (self.block_out_channels_a, self.block_out_channels_a * 2),
          '''layers_per_block''': 1,
          '''encoder_hid_dim''': self.text_embedder_hidden_size,
          '''encoder_hid_dim_type''': '''image_proj''',
          '''cross_attention_dim''': self.cross_attention_dim,
          '''attention_head_dim''': 4,
          '''resnet_time_scale_shift''': '''scale_shift''',
          '''class_embed_type''': None,
      }

      _UpperCAmelCase				:      Optional[Any]				=  UNetaDConditionModel(**__lowerCamelCase     )
      return model




   @property
   def      _lowerCAmelCase						(					self	:						int     )			->       List[Any]:







      """simple docstring"""




      return {
          "block_out_channels": [3_2, 6_4],
          "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
          "in_channels": 3,
          "latent_channels": 4,
          "layers_per_block": 1,
          "norm_num_groups": 8,
          "norm_type": "spatial",
          "num_vq_embeddings": 1_2,
          "out_channels": 3,
          "up_block_types": [
              "AttnUpDecoderBlock2D",
              "UpDecoderBlock2D",
          ],
          "vq_embed_dim": 4,
      }




   @property
   def      _lowerCAmelCase						(					self	:						Tuple     )			->       Union[str, Any]:







      """simple docstring"""




      torch.manual_seed(0     )
      _UpperCAmelCase				:      Tuple				=  VQModel(**self.dummy_movq_kwargs     )
      return model




   def      _lowerCAmelCase						(					self	:						str     )			->       Any:







      """simple docstring"""




      _UpperCAmelCase				:      List[Any]				=  self.dummy_unet
      _UpperCAmelCase				:      Optional[int]				=  self.dummy_movq

      _UpperCAmelCase				:      List[Any]				=  DDIMScheduler(
          num_train_timesteps=1_0_0_0		,	beta_schedule="linear"		,	beta_start=0.0_0085		,	beta_end=0.012		,	clip_sample=__lowerCamelCase		,	set_alpha_to_one=__lowerCamelCase		,	steps_offset=1		,	prediction_type="epsilon"		,	thresholding=__lowerCamelCase		,	)

      _UpperCAmelCase				:      Optional[int]				=  {
          '''unet''': unet,
          '''scheduler''': scheduler,
          '''movq''': movq,
      }
      return components




   def      _lowerCAmelCase						(					self	:						Tuple		,	lowerCAmelCase__	:						List[str]		,	lowerCAmelCase__	:						List[str]=0     )			->       List[str]:







      """simple docstring"""




      _UpperCAmelCase				:      Optional[int]				=  floats_tensor((1, self.text_embedder_hidden_size)		,	rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
      _UpperCAmelCase				:      List[Any]				=  floats_tensor((1, self.text_embedder_hidden_size)		,	rng=random.Random(seed + 1     )     ).to(
          __lowerCamelCase     )
      if str(__lowerCamelCase     ).startswith("mps"     ):
         _UpperCAmelCase				:      Optional[Any]				=  torch.manual_seed(__lowerCamelCase     )
      else:
         _UpperCAmelCase				:      Dict				=  torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
      _UpperCAmelCase				:      Dict				=  {
          '''image_embeds''': image_embeds,
          '''negative_image_embeds''': negative_image_embeds,
          '''generator''': generator,
          '''height''': 6_4,
          '''width''': 6_4,
          '''guidance_scale''': 4.0,
          '''num_inference_steps''': 2,
          '''output_type''': '''np''',
      }
      return inputs




   def      _lowerCAmelCase						(					self	:						Dict     )			->       Optional[Any]:







      """simple docstring"""




      _UpperCAmelCase				:      str				=  '''cpu'''

      _UpperCAmelCase				:      str				=  self.get_dummy_components()

      _UpperCAmelCase				:      Dict				=  self.pipeline_class(**__lowerCamelCase     )
      _UpperCAmelCase				:      Tuple				=  pipe.to(__lowerCamelCase     )

      pipe.set_progress_bar_config(disable=__lowerCamelCase     )

      _UpperCAmelCase				:      List[str]				=  pipe(**self.get_dummy_inputs(__lowerCamelCase     )     )
      _UpperCAmelCase				:      Tuple				=  output.images

      _UpperCAmelCase				:      Tuple				=  pipe(
          **self.get_dummy_inputs(__lowerCamelCase     )		,	return_dict=__lowerCamelCase		,	)[0]

      _UpperCAmelCase				:      Dict				=  image[0, -3:, -3:, -1]
      _UpperCAmelCase				:      Any				=  image_from_tuple[0, -3:, -3:, -1]

      assert image.shape == (1, 6_4, 6_4, 3)

      _UpperCAmelCase				:      Optional[int]				=  np.array(
          [0.623_7976, 1.0, 0.3644_1332, 1.0, 0.7063_9634, 0.2987_7186, 0.8565_2125, 0.521_6843, 0.5445_4046]     )

      assert (
          np.abs(image_slice.flatten() - expected_slice     ).max() < 1e-2
      ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}"""

      assert (
          np.abs(image_from_tuple_slice.flatten() - expected_slice     ).max() < 1e-2
      ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"""





@slow
@require_torch_gpu
class        A__				(			unittest.TestCase  ):





   """simple docstring"""





   def      _lowerCAmelCase						(					self	:						Optional[Any]     )			->       Dict:







      """simple docstring"""




      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()




   def      _lowerCAmelCase						(					self	:						List[str]     )			->       Dict:







      """simple docstring"""




      _UpperCAmelCase				:      Any				=  load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy"     )

      _UpperCAmelCase				:      Optional[Any]				=  KandinskyVaaPriorPipeline.from_pretrained(
          "kandinsky-community/kandinsky-2-2-prior"		,	torch_dtype=torch.floataa     )
      pipe_prior.to(__lowerCamelCase     )

      _UpperCAmelCase				:      int				=  KandinskyVaaPipeline.from_pretrained(
          "kandinsky-community/kandinsky-2-2-decoder"		,	torch_dtype=torch.floataa     )
      _UpperCAmelCase				:      Union[str, Any]				=  pipeline.to(__lowerCamelCase     )
      pipeline.set_progress_bar_config(disable=__lowerCamelCase     )

      _UpperCAmelCase				:      List[Any]				=  '''red cat, 4k photo'''

      _UpperCAmelCase				:      Union[str, Any]				=  torch.Generator(device="cuda"     ).manual_seed(0     )
      _UpperCAmelCase				:      List[str]				=  pipe_prior(
          __lowerCamelCase		,	generator=__lowerCamelCase		,	num_inference_steps=5		,	negative_prompt=""		,	).to_tuple()

      _UpperCAmelCase				:      Any				=  torch.Generator(device="cuda"     ).manual_seed(0     )
      _UpperCAmelCase				:      Optional[int]				=  pipeline(
          image_embeds=__lowerCamelCase		,	negative_image_embeds=__lowerCamelCase		,	generator=__lowerCamelCase		,	num_inference_steps=1_0_0		,	output_type="np"		,	)

      _UpperCAmelCase				:      Union[str, Any]				=  output.images[0]

      assert image.shape == (5_1_2, 5_1_2, 3)

      assert_mean_pixel_difference(__lowerCamelCase		,	__lowerCamelCase     )






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




