



import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import PriorTransformer, UnCLIPPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel
from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel
from diffusers.utils import load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, skip_mps

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()







class 						snake_case  (		SCREAMING_SNAKE_CASE_   ,unittest.TestCase					):



   '''simple docstring'''






   snake_case_   :	List[Any]       =						UnCLIPPipeline
   snake_case_   :	Optional[Any]       =						TEXT_TO_IMAGE_PARAMS - {
       """negative_prompt""",
       """height""",
       """width""",
       """negative_prompt_embeds""",
       """guidance_scale""",
       """prompt_embeds""",
       """cross_attention_kwargs""",
   }
   snake_case_   :	Any       =						TEXT_TO_IMAGE_BATCH_PARAMS
   snake_case_   :	Any       =						[
       """generator""",
       """return_dict""",
       """prior_num_inference_steps""",
       """decoder_num_inference_steps""",
       """super_res_num_inference_steps""",
   ]
   snake_case_   :	Any       =						False

   @property
   def        UpperCamelCase_					(   self							:     Any)			->			int:

    """simple docstring"""







    return 32

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

    """simple docstring"""







    return 32

   @property
   def        UpperCamelCase_					(   self							:     Tuple)			->			int:

    """simple docstring"""







    return self.time_input_dim

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

    """simple docstring"""







    return self.time_input_dim * 4

   @property
   def        UpperCamelCase_					(   self							:     Union[str, Any])			->			Optional[int]:

    """simple docstring"""







    return 100

   @property
   def        UpperCamelCase_					(   self							:     List[str])			->			Dict:

    """simple docstring"""







    _snake_case      :					Union[str, Any]					=   CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")
    return tokenizer

   @property
   def        UpperCamelCase_					(   self							:     Optional[int])			->			List[str]:

    """simple docstring"""







    torch.manual_seed(0)
    _snake_case      :					Tuple					=   CLIPTextConfig(
        bos_token_id=0			,						eos_token_id=2			,						hidden_size=self.text_embedder_hidden_size			,						projection_dim=self.text_embedder_hidden_size			,						intermediate_size=37			,						layer_norm_eps=1E-05			,						num_attention_heads=4			,						num_hidden_layers=5			,						pad_token_id=1			,						vocab_size=1000			,						)
    return CLIPTextModelWithProjection(lowerCAmelCase)

   @property
   def        UpperCamelCase_					(   self							:     Any)			->			int:

    """simple docstring"""







    torch.manual_seed(0)

    _snake_case      :					Tuple					=   {
        """num_attention_heads""": 2,
        """attention_head_dim""": 12,
        """embedding_dim""": self.text_embedder_hidden_size,
        """num_layers""": 1,
    }

    _snake_case      :					Dict					=   PriorTransformer(**lowerCAmelCase)
    return model

   @property
   def        UpperCamelCase_					(   self							:     int)			->			int:

    """simple docstring"""







    torch.manual_seed(0)

    _snake_case      :					List[Any]					=   {
        """clip_embeddings_dim""": self.text_embedder_hidden_size,
        """time_embed_dim""": self.time_embed_dim,
        """cross_attention_dim""": self.cross_attention_dim,
    }

    _snake_case      :					Union[str, Any]					=   UnCLIPTextProjModel(**lowerCAmelCase)
    return model

   @property
   def        UpperCamelCase_					(   self							:     Optional[int])			->			List[str]:

    """simple docstring"""







    torch.manual_seed(0)

    _snake_case      :					Optional[int]					=   {
        """sample_size""": 32,
        # RGB in channels
        """in_channels""": 3,
        # Out channels is double in channels because predicts mean and variance
        """out_channels""": 6,
        """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,
        """cross_attention_dim""": self.cross_attention_dim,
        """attention_head_dim""": 4,
        """resnet_time_scale_shift""": """scale_shift""",
        """class_embed_type""": """identity""",
    }

    _snake_case      :					int					=   UNetaDConditionModel(**lowerCAmelCase)
    return model

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

    """simple docstring"""







    return {
        "sample_size": 64,
        "layers_per_block": 1,
        "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),
        "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),
        "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
        "in_channels": 6,
        "out_channels": 3,
    }

   @property
   def        UpperCamelCase_					(   self							:     Tuple)			->			int:

    """simple docstring"""







    torch.manual_seed(0)

    _snake_case      :					Union[str, Any]					=   UNetaDModel(**self.dummy_super_res_kwargs)
    return model

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

    """simple docstring"""







    torch.manual_seed(1)

    _snake_case      :					str					=   UNetaDModel(**self.dummy_super_res_kwargs)
    return model

   def        UpperCamelCase_					(   self							:     int)			->			Any:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   self.dummy_prior
    _snake_case      :					Optional[Any]					=   self.dummy_decoder
    _snake_case      :					Tuple					=   self.dummy_text_proj
    _snake_case      :					Optional[Any]					=   self.dummy_text_encoder
    _snake_case      :					Any					=   self.dummy_tokenizer
    _snake_case      :					Union[str, Any]					=   self.dummy_super_res_first
    _snake_case      :					Union[str, Any]					=   self.dummy_super_res_last

    _snake_case      :					Any					=   UnCLIPScheduler(
        variance_type="""fixed_small_log"""			,						prediction_type="""sample"""			,						num_train_timesteps=1000			,						clip_sample_range=5.0			,						)

    _snake_case      :					Tuple					=   UnCLIPScheduler(
        variance_type="""learned_range"""			,						prediction_type="""epsilon"""			,						num_train_timesteps=1000			,						)

    _snake_case      :					Dict					=   UnCLIPScheduler(
        variance_type="""fixed_small_log"""			,						prediction_type="""epsilon"""			,						num_train_timesteps=1000			,						)

    _snake_case      :					str					=   {
        """prior""": prior,
        """decoder""": decoder,
        """text_proj""": text_proj,
        """text_encoder""": text_encoder,
        """tokenizer""": tokenizer,
        """super_res_first""": super_res_first,
        """super_res_last""": super_res_last,
        """prior_scheduler""": prior_scheduler,
        """decoder_scheduler""": decoder_scheduler,
        """super_res_scheduler""": super_res_scheduler,
    }

    return components

   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Dict			,						lowerCAmelCase							:     List[str]=0)			->			Any:

    """simple docstring"""







    if str(lowerCAmelCase).startswith("""mps"""):
     _snake_case      :					Tuple					=   torch.manual_seed(lowerCAmelCase)
    else:
     _snake_case      :					Optional[Any]					=   torch.Generator(device=lowerCAmelCase).manual_seed(lowerCAmelCase)
    _snake_case      :					List[Any]					=   {
        """prompt""": """horse""",
        """generator""": generator,
        """prior_num_inference_steps""": 2,
        """decoder_num_inference_steps""": 2,
        """super_res_num_inference_steps""": 2,
        """output_type""": """numpy""",
    }
    return inputs

   def        UpperCamelCase_					(   self							:     Optional[Any])			->			Any:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   """cpu"""

    _snake_case      :					List[Any]					=   self.get_dummy_components()

    _snake_case      :					str					=   self.pipeline_class(**lowerCAmelCase)
    _snake_case      :					Any					=   pipe.to(lowerCAmelCase)

    pipe.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Optional[int]					=   pipe(**self.get_dummy_inputs(lowerCAmelCase))
    _snake_case      :					Union[str, Any]					=   output.images

    _snake_case      :					List[str]					=   pipe(
        **self.get_dummy_inputs(lowerCAmelCase)			,						return_dict=lowerCAmelCase			,						)[0]

    _snake_case      :					Dict					=   image[0, -3:, -3:, -1]
    _snake_case      :					Optional[int]					=   image_from_tuple[0, -3:, -3:, -1]

    assert image.shape == (1, 64, 64, 3)

    _snake_case      :					str					=   np.array(
        [
            0.9_997,
            0.9_988,
            0.0_028,
            0.9_997,
            0.9_984,
            0.9_965,
            0.0_029,
            0.9_986,
            0.0_025,
        ])

    assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
    assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1E-2

   def        UpperCamelCase_					(   self							:     int)			->			Any:

    """simple docstring"""







    _snake_case      :					int					=   torch.device("""cpu""")







    class 						snake_case  :



       '''simple docstring'''






       snake_case_   :	List[Any]       =						1
    _snake_case      :					Any					=   self.get_dummy_components()

    _snake_case      :					Optional[int]					=   self.pipeline_class(**lowerCAmelCase)
    _snake_case      :					Union[str, Any]					=   pipe.to(lowerCAmelCase)

    _snake_case      :					str					=   components["""prior"""]
    _snake_case      :					int					=   components["""decoder"""]
    _snake_case      :					Any					=   components["""super_res_first"""]
    _snake_case      :					Union[str, Any]					=   components["""tokenizer"""]
    _snake_case      :					Any					=   components["""text_encoder"""]

    _snake_case      :					Tuple					=   torch.Generator(device=lowerCAmelCase).manual_seed(0)
    _snake_case      :					str					=   prior.dtype
    _snake_case      :					Any					=   1

    _snake_case      :					Any					=   (batch_size, prior.config.embedding_dim)
    _snake_case      :					List[str]					=   pipe.prepare_latents(
        lowerCAmelCase			,						dtype=lowerCAmelCase			,						device=lowerCAmelCase			,						generator=lowerCAmelCase			,						latents=lowerCAmelCase			,						scheduler=DummyScheduler())
    _snake_case      :					Dict					=   (batch_size, decoder.config.in_channels, decoder.config.sample_size, decoder.config.sample_size)
    _snake_case      :					str					=   pipe.prepare_latents(
        lowerCAmelCase			,						dtype=lowerCAmelCase			,						device=lowerCAmelCase			,						generator=lowerCAmelCase			,						latents=lowerCAmelCase			,						scheduler=DummyScheduler())

    _snake_case      :					Union[str, Any]					=   (
        batch_size,
        super_res_first.config.in_channels // 2,
        super_res_first.config.sample_size,
        super_res_first.config.sample_size,
    )
    _snake_case      :					Union[str, Any]					=   pipe.prepare_latents(
        lowerCAmelCase			,						dtype=lowerCAmelCase			,						device=lowerCAmelCase			,						generator=lowerCAmelCase			,						latents=lowerCAmelCase			,						scheduler=DummyScheduler())

    pipe.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Union[str, Any]					=   """this is a prompt example"""

    _snake_case      :					List[Any]					=   torch.Generator(device=lowerCAmelCase).manual_seed(0)
    _snake_case      :					Any					=   pipe(
        [prompt]			,						generator=lowerCAmelCase			,						prior_num_inference_steps=2			,						decoder_num_inference_steps=2			,						super_res_num_inference_steps=2			,						prior_latents=lowerCAmelCase			,						decoder_latents=lowerCAmelCase			,						super_res_latents=lowerCAmelCase			,						output_type="""np"""			,						)
    _snake_case      :					Union[str, Any]					=   output.images

    _snake_case      :					Optional[int]					=   tokenizer(
        lowerCAmelCase			,						padding="""max_length"""			,						max_length=tokenizer.model_max_length			,						return_tensors="""pt"""			,						)
    _snake_case      :					Union[str, Any]					=   text_encoder(text_inputs.input_ids)
    _snake_case      :					Union[str, Any]					=   text_inputs.attention_mask

    _snake_case      :					str					=   torch.Generator(device=lowerCAmelCase).manual_seed(0)
    _snake_case      :					str					=   pipe(
        generator=lowerCAmelCase			,						prior_num_inference_steps=2			,						decoder_num_inference_steps=2			,						super_res_num_inference_steps=2			,						prior_latents=lowerCAmelCase			,						decoder_latents=lowerCAmelCase			,						super_res_latents=lowerCAmelCase			,						text_model_output=lowerCAmelCase			,						text_attention_mask=lowerCAmelCase			,						output_type="""np"""			,						)[0]

    # make sure passing text embeddings manually is identical
    assert np.abs(image - image_from_text).max() < 1E-4

   @skip_mps
   def        UpperCamelCase_					(   self							:     str)			->			Tuple:

    """simple docstring"""







    _snake_case      :					Tuple					=   torch_device == """cpu"""

    self._test_attention_slicing_forward_pass(test_max_difference=lowerCAmelCase			,						expected_max_diff=0.01)

   @skip_mps
   def        UpperCamelCase_					(   self							:     Tuple)			->			Union[str, Any]:

    """simple docstring"""







    _snake_case      :					Tuple					=   torch_device == """cpu"""
    _snake_case      :					Dict					=   True
    _snake_case      :					Tuple					=   [
        """prior_num_inference_steps""",
        """decoder_num_inference_steps""",
        """super_res_num_inference_steps""",
    ]

    self._test_inference_batch_single_identical(
        test_max_difference=lowerCAmelCase			,						relax_max_difference=lowerCAmelCase			,						additional_params_copy_to_batched_inputs=lowerCAmelCase			,						)

   def        UpperCamelCase_					(   self							:     Union[str, Any])			->			Dict:

    """simple docstring"""







    _snake_case      :					Optional[int]					=   [
        """prior_num_inference_steps""",
        """decoder_num_inference_steps""",
        """super_res_num_inference_steps""",
    ]

    if torch_device == "mps":
     # TODO: MPS errors with larger batch sizes
     _snake_case      :					Any					=   [2, 3]
     self._test_inference_batch_consistent(
         batch_sizes=lowerCAmelCase			,						additional_params_copy_to_batched_inputs=lowerCAmelCase			,						)
    else:
     self._test_inference_batch_consistent(
         additional_params_copy_to_batched_inputs=lowerCAmelCase)

   @skip_mps
   def        UpperCamelCase_					(   self							:     Tuple)			->			Dict:

    """simple docstring"""







    return super().test_dict_tuple_outputs_equivalent()

   @skip_mps
   def        UpperCamelCase_					(   self							:     str)			->			Dict:

    """simple docstring"""







    return super().test_save_load_local()


   @skip_mps
   def        UpperCamelCase_					(   self							:     str)			->			Optional[int]:

    """simple docstring"""







    return super().test_save_load_optional_components()







@nightly
class 						snake_case  (		unittest.TestCase					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Any)			->			str:

    """simple docstring"""







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


   def        UpperCamelCase_					(   self							:     Optional[int])			->			Optional[int]:

    """simple docstring"""







    _snake_case      :					int					=   load_numpy(
        """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
        """/unclip/karlo_v1_alpha_horse_cpu.npy""")

    _snake_case      :					Any					=   UnCLIPPipeline.from_pretrained("""kakaobrain/karlo-v1-alpha""")
    pipeline.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Optional[int]					=   torch.manual_seed(0)
    _snake_case      :					Any					=   pipeline(
        """horse"""			,						num_images_per_prompt=1			,						generator=lowerCAmelCase			,						output_type="""np"""			,						)

    _snake_case      :					str					=   output.images[0]

    assert image.shape == (256, 256, 3)
    assert np.abs(expected_image - image).max() < 1E-1







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



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Optional[int])			->			Optional[int]:

    """simple docstring"""







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

   def        UpperCamelCase_					(   self							:     Dict)			->			int:

    """simple docstring"""







    _snake_case      :					Union[str, Any]					=   load_numpy(
        """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
        """/unclip/karlo_v1_alpha_horse_fp16.npy""")

    _snake_case      :					Dict					=   UnCLIPPipeline.from_pretrained("""kakaobrain/karlo-v1-alpha"""			,						torch_dtype=torch.floataa)
    _snake_case      :					Optional[Any]					=   pipeline.to(lowerCAmelCase)
    pipeline.set_progress_bar_config(disable=lowerCAmelCase)

    _snake_case      :					Optional[int]					=   torch.Generator(device="""cpu""").manual_seed(0)
    _snake_case      :					Dict					=   pipeline(
        """horse"""			,						generator=lowerCAmelCase			,						output_type="""np"""			,						)

    _snake_case      :					Optional[int]					=   output.images[0]

    assert image.shape == (256, 256, 3)

    assert_mean_pixel_difference(lowerCAmelCase			,						lowerCAmelCase)


   def        UpperCamelCase_					(   self							:     Any)			->			Any:

    """simple docstring"""







    torch.cuda.empty_cache()
    torch.cuda.reset_max_memory_allocated()
    torch.cuda.reset_peak_memory_stats()

    _snake_case      :					str					=   UnCLIPPipeline.from_pretrained("""kakaobrain/karlo-v1-alpha"""			,						torch_dtype=torch.floataa)
    _snake_case      :					Dict					=   pipe.to(lowerCAmelCase)
    pipe.set_progress_bar_config(disable=lowerCAmelCase)
    pipe.enable_attention_slicing()
    pipe.enable_sequential_cpu_offload()

    _snake_case      :					Dict					=   pipe(
        """horse"""			,						num_images_per_prompt=1			,						prior_num_inference_steps=2			,						decoder_num_inference_steps=2			,						super_res_num_inference_steps=2			,						output_type="""np"""			,						)

    _snake_case      :					List[str]					=   torch.cuda.max_memory_allocated()
    # make sure that less than 7 GB is allocated
    assert mem_bytes < 7 * 10**9





import os
import warnings
from pathlib import Path
from typing import Optional, Union

from .dynamic_module_utils import custom_object_save
from .tokenization_utils_base import PreTrainedTokenizerBase
from .utils import PushToHubMixin, copy_func, direct_transformers_import, logging


a__      =		logging.get_logger(__name__)

# Dynamically import the Transformers module to grab the attribute classes of the processor form their names.
a__      =		direct_transformers_import(Path(__file__).parent)


a__      =		{
    """AutoTokenizer""": """PreTrainedTokenizerBase""",
    """AutoFeatureExtractor""": """FeatureExtractionMixin""",
    """AutoImageProcessor""": """ImageProcessingMixin""",
}







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   snake_case_   :	List[str]       =						["""feature_extractor""", """tokenizer"""]
   # Names need to be attr_class for attr in attributes
   snake_case_   :	Optional[Any]       =						None
   snake_case_   :	List[str]       =						None
   snake_case_   :	List[str]       =						None

   def __init__(   self							:     int			,						*lowerCAmelCase							:     Any			,						**lowerCAmelCase							:     int)			->			Optional[Any]:

    """simple docstring"""







    for key in kwargs:
     if key not in self.attributes:
      raise TypeError(F'''Unexpected keyword argument {key}.''')
    for arg, attribute_name in zip(lowerCAmelCase			,						self.attributes):
     if attribute_name in kwargs:
      raise TypeError(F'''Got multiple values for argument {attribute_name}.''')
     else:
      _snake_case      :					List[str]					=   arg

    if len(lowerCAmelCase) != len(self.attributes):
     raise ValueError(
         F'''This processor requires {len(self.attributes)} arguments: {', '.join(self.attributes)}. Got '''
         F'''{len(lowerCAmelCase)} arguments instead.''')

    # Check each arg is of the proper class (this will also catch a user initializing in the wrong order)
    for attribute_name, arg in kwargs.items():
     _snake_case      :					Optional[Any]					=   getattr(self			,						F'''{attribute_name}_class''')
     # Nothing is ever going to be an instance of "AutoXxx", in that case we check the base class.
     _snake_case      :					List[str]					=   AUTO_TO_BASE_CLASS_MAPPING.get(lowerCAmelCase			,						lowerCAmelCase)
     if isinstance(lowerCAmelCase			,						lowerCAmelCase):
      _snake_case      :					Optional[Any]					=   tuple(getattr(lowerCAmelCase			,						lowerCAmelCase) for n in class_name if n is not None)
     else:
      _snake_case      :					List[Any]					=   getattr(lowerCAmelCase			,						lowerCAmelCase)

     if not isinstance(lowerCAmelCase			,						lowerCAmelCase):
      raise ValueError(
          F'''Received a {type(lowerCAmelCase).__name__} for argument {attribute_name}, but a {class_name} was expected.''')

     setattr(self			,						lowerCAmelCase			,						lowerCAmelCase)

   def __repr__(   self							:     int)			->			Dict:

    """simple docstring"""







    _snake_case      :					Union[str, Any]					=   [F'''- {name}: {repr(getattr(self			,						lowerCAmelCase))}''' for name in self.attributes]
    _snake_case      :					str					=   """\n""".join(lowerCAmelCase)
    return F'''{self.__class__.__name__}:\n{attributes_repr}'''

   def        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Optional[int]			,						lowerCAmelCase							:     bool = False			,						**lowerCAmelCase							:     Union[str, Any])			->			Dict:

    """simple docstring"""







    os.makedirs(lowerCAmelCase			,						exist_ok=lowerCAmelCase)

    if push_to_hub:
     _snake_case      :					str					=   kwargs.pop("""commit_message"""			,						lowerCAmelCase)
     _snake_case      :					Union[str, Any]					=   kwargs.pop("""repo_id"""			,						save_directory.split(os.path.sep)[-1])
     _snake_case      :					Tuple					=   self._create_repo(lowerCAmelCase			,						**lowerCAmelCase)
     _snake_case      :					Any					=   self._get_files_timestamps(lowerCAmelCase)
    # If we have a custom config, we copy the file defining it in the folder and set the attributes so it can be
    # loaded from the Hub.
    if self._auto_class is not None:
     _snake_case      :					Any					=   [getattr(self			,						lowerCAmelCase) for attribute_name in self.attributes]
     _snake_case      :					Any					=   [(a.init_kwargs if isinstance(lowerCAmelCase			,						lowerCAmelCase) else a) for a in attrs]
     custom_object_save(self			,						lowerCAmelCase			,						config=lowerCAmelCase)

    for attribute_name in self.attributes:
     _snake_case      :					Optional[int]					=   getattr(self			,						lowerCAmelCase)
     # Include the processor class in the attribute config so this processor can then be reloaded with the
     # `AutoProcessor` API.
     if hasattr(lowerCAmelCase			,						"""_set_processor_class"""):
      attribute._set_processor_class(self.__class__.__name__)
     attribute.save_pretrained(lowerCAmelCase)

    if self._auto_class is not None:
     # We added an attribute to the init_kwargs of the tokenizers, which needs to be cleaned up.
     for attribute_name in self.attributes:
      _snake_case      :					List[str]					=   getattr(self			,						lowerCAmelCase)
      if isinstance(lowerCAmelCase			,						lowerCAmelCase):
       del attribute.init_kwargs["auto_map"]

    if push_to_hub:
     self._upload_modified_files(
         lowerCAmelCase			,						lowerCAmelCase			,						lowerCAmelCase			,						commit_message=lowerCAmelCase			,						token=kwargs.get("""use_auth_token""")			,						)

   @classmethod
   def        UpperCamelCase_					(   cls							:     List[Any]			,						lowerCAmelCase							:     Union[str, os.PathLike]			,						lowerCAmelCase							:     Optional[Union[str, os.PathLike]] = None			,						lowerCAmelCase							:     bool = False			,						lowerCAmelCase							:     bool = False			,						lowerCAmelCase							:     Optional[Union[str, bool]] = None			,						lowerCAmelCase							:     str = "main"			,						**lowerCAmelCase							:     Dict			,						)			->			Tuple:

    """simple docstring"""







    _snake_case      :					Dict					=   cache_dir
    _snake_case      :					Optional[Any]					=   force_download
    _snake_case      :					Dict					=   local_files_only
    _snake_case      :					Any					=   revision

    _snake_case      :					Dict					=   kwargs.pop("""use_auth_token"""			,						lowerCAmelCase)
    if use_auth_token is not None:
     warnings.warn(
         """The `use_auth_token` argument is deprecated and will be removed in v5 of Transformers."""			,						lowerCAmelCase)
     if token is not None:
      raise ValueError(
          """`token` and `use_auth_token` are both specified. Please set only the argument `token`.""")
     _snake_case      :					str					=   use_auth_token

    if token is not None:
     # change to `token` in a follow-up PR
     _snake_case      :					Tuple					=   token

    _snake_case      :					Tuple					=   cls._get_arguments_from_pretrained(lowerCAmelCase			,						**lowerCAmelCase)
    return cls(*lowerCAmelCase)

   @classmethod
   def        UpperCamelCase_					(   cls							:     Optional[Any]			,						lowerCAmelCase							:     str="AutoProcessor")			->			int:

    """simple docstring"""







    if not isinstance(lowerCAmelCase			,						lowerCAmelCase):
     _snake_case      :					List[Any]					=   auto_class.__name__

    import transformers.models.auto as auto_module

    if not hasattr(lowerCAmelCase			,						lowerCAmelCase):
     raise ValueError(F'''{auto_class} is not a valid auto class.''')

    _snake_case      :					List[str]					=   auto_class

   @classmethod
   def        UpperCamelCase_					(   cls							:     List[Any]			,						lowerCAmelCase							:     Any			,						**lowerCAmelCase							:     Union[str, Any])			->			Optional[Any]:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   []
    for attribute_name in cls.attributes:
     _snake_case      :					Optional[Any]					=   getattr(cls			,						F'''{attribute_name}_class''')
     if isinstance(lowerCAmelCase			,						lowerCAmelCase):
      _snake_case      :					Tuple					=   tuple(getattr(lowerCAmelCase			,						lowerCAmelCase) if n is not None else None for n in class_name)
      _snake_case      :					str					=   kwargs.get("""use_fast"""			,						lowerCAmelCase)
      if use_fast and classes[1] is not None:
       _snake_case      :					Any					=   classes[1]
      else:
       _snake_case      :					Union[str, Any]					=   classes[0]
     else:
      _snake_case      :					Optional[Any]					=   getattr(lowerCAmelCase			,						lowerCAmelCase)

     args.append(attribute_class.from_pretrained(lowerCAmelCase			,						**lowerCAmelCase))
    return args


   @property
   def        UpperCamelCase_					(   self							:     Optional[int])			->			str:

    """simple docstring"""







    _snake_case      :					Tuple					=   getattr(self			,						self.attributes[0])
    return getattr(lowerCAmelCase			,						"""model_input_names"""			,						lowerCAmelCase)
a__      =		copy_func(ProcessorMixin.push_to_hub)
if ProcessorMixin.push_to_hub.__doc__ is not None:
  a__      =		ProcessorMixin.push_to_hub.__doc__.format(
      object="""processor""", object_class="""AutoProcessor""", object_files="""processor files"""
  )
