


'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


__UpperCAmelCase     :Optional[int]												=  logging.get_logger(__name__)  # pylint: disable=invalid-name

__UpperCAmelCase     :List[str]												=  """
    Examples:
        ```py
        >>> import torch
        >>> import numpy as np

        >>> from diffusers import KandinskyV22PriorEmb2EmbPipeline, KandinskyV22ControlnetImg2ImgPipeline
        >>> from transformers import pipeline
        >>> from diffusers.utils import load_image


        >>> def make_hint(image, depth_estimator):
        ...     image = depth_estimator(image)[\"depth\"]
        ...     image = np.array(image)
        ...     image = image[:, :, None]
        ...     image = np.concatenate([image, image, image], axis=2)
        ...     detected_map = torch.from_numpy(image).float() / 255.0
        ...     hint = detected_map.permute(2, 0, 1)
        ...     return hint


        >>> depth_estimator = pipeline(\"depth-estimation\")

        >>> pipe_prior = KandinskyV22PriorEmb2EmbPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16
        ... )
        >>> pipe_prior = pipe_prior.to(\"cuda\")

        >>> pipe = KandinskyV22ControlnetImg2ImgPipeline.from_pretrained(
        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16
        ... )
        >>> pipe = pipe.to(\"cuda\")

        >>> img = load_image(
        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"
        ...     \"/kandinsky/cat.png\"
        ... ).resize((768, 768))


        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")

        >>> prompt = \"A robot, 4k photo\"
        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"

        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)

        >>> img_emb = pipe_prior(prompt=prompt, image=img, strength=0.85, generator=generator)
        >>> negative_emb = pipe_prior(prompt=negative_prior_prompt, image=img, strength=1, generator=generator)

        >>> images = pipe(
        ...     image=img,
        ...     strength=0.5,
        ...     image_embeds=img_emb.image_embeds,
        ...     negative_image_embeds=negative_emb.image_embeds,
        ...     hint=hint,
        ...     num_inference_steps=50,
        ...     generator=generator,
        ...     height=768,
        ...     width=768,
        ... ).images

        >>> images[0].save(\"robot_cat.png\")
        ```
"""




def       _a      (		_lowercase   :      str     ,   _lowercase   :      Union[str, Any]     ,   _lowercase   :      Any=8    ):





     '''simple docstring'''






     __UpperCAmelCase      :					int    				=     height // scale_factor**2
     if height % scale_factor**2 != 0:
          new_height += 1
     __UpperCAmelCase      :					List[Any]    				=     width // scale_factor**2
     if width % scale_factor**2 != 0:
          new_width += 1
     return new_height * scale_factor, new_width * scale_factor




def       _a      (		_lowercase   :      Any     ,   _lowercase   :      str=512     ,   _lowercase   :      List[Any]=512    ):





     '''simple docstring'''






     __UpperCAmelCase      :					Tuple    				=     pil_image.resize((w, h)     ,   resample=Image.BICUBIC     ,   reducing_gap=1    )
     __UpperCAmelCase      :					int    				=     np.array(pil_image.convert('''RGB'''    )    )
     __UpperCAmelCase      :					List[str]    				=     arr.astype(np.floataa    ) / 127.5 - 1
     __UpperCAmelCase      :					Optional[int]    				=     np.transpose(_UpperCAmelCase     ,   [2, 0, 1]    )
     __UpperCAmelCase      :					Any    				=     torch.from_numpy(_UpperCAmelCase    ).unsqueeze(0    )
     return image



class       a							(						__lowerCAmelCase			):


     """simple docstring"""






     def __init__(							self	:						Optional[Any]				,					snake_case	:						Dict				,					snake_case	:						int				,					snake_case	:						int				,					)		->				Dict:
          super().__init__()

          self.register_modules(
              unet=__SCREAMING_SNAKE_CASE				,					scheduler=__SCREAMING_SNAKE_CASE				,					movq=__SCREAMING_SNAKE_CASE				,					)
          __UpperCAmelCase      :					Dict    				=     2 ** (len(self.movq.config.block_out_channels     ) - 1)

     def 					lowerCamelCase__					(							self	:						List[str]				,					snake_case	:						Any				,					snake_case	:						Optional[int]				,					snake_case	:						Dict     )		->				Optional[int]:
          __UpperCAmelCase      :					Tuple    				=     min(int(num_inference_steps * strength     )				,					__SCREAMING_SNAKE_CASE     )

          __UpperCAmelCase      :					Union[str, Any]    				=     max(num_inference_steps - init_timestep				,					0     )
          __UpperCAmelCase      :					Union[str, Any]    				=     self.scheduler.timesteps[t_start:]

          return timesteps, num_inference_steps - t_start

     def 					lowerCamelCase__					(							self	:						Optional[int]				,					snake_case	:						Any				,					snake_case	:						Any				,					snake_case	:						int				,					snake_case	:						List[Any]				,					snake_case	:						Union[str, Any]				,					snake_case	:						Any				,					snake_case	:						int=None     )		->				List[Any]:

          if not isinstance(__SCREAMING_SNAKE_CASE				,					(torch.Tensor, PIL.Image.Image, list)     ):
               raise ValueError(
                   f'`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(__SCREAMING_SNAKE_CASE     )}'     )

          __UpperCAmelCase      :					int    				=     image.to(device=__SCREAMING_SNAKE_CASE				,					dtype=__SCREAMING_SNAKE_CASE     )

          __UpperCAmelCase      :					List[str]    				=     batch_size * num_images_per_prompt

          if image.shape[1] == 4:
               __UpperCAmelCase      :					Optional[Any]    				=     image

          else:
               if isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ) and len(__SCREAMING_SNAKE_CASE     ) != batch_size:
                    raise ValueError(
                        f'You have passed a list of generators of length {len(__SCREAMING_SNAKE_CASE     )}, but requested an effective batch'
                        f' size of {batch_size}. Make sure the batch size matches the length of the generators.'     )

               elif isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ):
                    __UpperCAmelCase      :					Tuple    				=     [
                        self.movq.encode(image[i : i + 1]     ).latent_dist.sample(generator[i]     ) for i in range(__SCREAMING_SNAKE_CASE     )
                    ]
                    __UpperCAmelCase      :					List[str]    				=     torch.cat(__SCREAMING_SNAKE_CASE				,					dim=0     )
               else:
                    __UpperCAmelCase      :					List[str]    				=     self.movq.encode(__SCREAMING_SNAKE_CASE     ).latent_dist.sample(__SCREAMING_SNAKE_CASE     )

               __UpperCAmelCase      :					str    				=     self.movq.config.scaling_factor * init_latents

          __UpperCAmelCase      :					List[Any]    				=     torch.cat([init_latents]				,					dim=0     )

          __UpperCAmelCase      :					List[Any]    				=     init_latents.shape
          __UpperCAmelCase      :					int    				=     randn_tensor(__SCREAMING_SNAKE_CASE				,					generator=__SCREAMING_SNAKE_CASE				,					device=__SCREAMING_SNAKE_CASE				,					dtype=__SCREAMING_SNAKE_CASE     )

          # get latents
          __UpperCAmelCase      :					int    				=     self.scheduler.add_noise(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     )

          __UpperCAmelCase      :					str    				=     init_latents

          return latents

     def 					lowerCamelCase__					(							self	:						Dict				,					snake_case	:						Union[str, Any]=0     )		->				int:

          if is_accelerate_available():
               from accelerate import cpu_offload
          else:
               raise ImportError('''Please install accelerate via `pip install accelerate`'''     )

          __UpperCAmelCase      :					Union[str, Any]    				=     torch.device(f'cuda:{gpu_id}'     )

          __UpperCAmelCase      :					Any    				=     [
              self.unet,
              self.movq,
          ]
          for cpu_offloaded_model in models:
               if cpu_offloaded_model is not None:
                    cpu_offload(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     )

     def 					lowerCamelCase__					(							self	:						Optional[Any]				,					snake_case	:						Union[str, Any]=0     )		->				int:

          if is_accelerate_available() and is_accelerate_version('''>='''				,					'''0.17.0.dev0'''     ):
               from accelerate import cpu_offload_with_hook
          else:
               raise ImportError('''`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.'''     )

          __UpperCAmelCase      :					Optional[Any]    				=     torch.device(f'cuda:{gpu_id}'     )

          if self.device.type != "cpu":
               self.to('''cpu'''				,					silence_dtype_warnings=__SCREAMING_SNAKE_CASE     )
               torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

          __UpperCAmelCase      :					str    				=     None
          for cpu_offloaded_model in [self.unet, self.movq]:
               __UpperCAmelCase				,  __UpperCAmelCase      :					List[str]    				=     cpu_offload_with_hook(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					prev_module_hook=__SCREAMING_SNAKE_CASE     )

          # We'll offload the last model manually.
          __UpperCAmelCase      :					Union[str, Any]    				=     hook

     @property
     # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
     def 					lowerCamelCase__					(							self	:						Any     )		->				Optional[Any]:

          if not hasattr(self.unet				,					'''_hf_hook'''     ):
               return self.device
          for module in self.unet.modules():
               if (
                   hasattr(__SCREAMING_SNAKE_CASE				,					'''_hf_hook'''     )
                   and hasattr(module._hf_hook				,					'''execution_device'''     )
                   and module._hf_hook.execution_device is not None
               ):
                    return torch.device(module._hf_hook.execution_device     )
          return self.device






     @torch.no_grad()
     @replace_example_docstring(__SCREAMING_SNAKE_CASE     )
     def __call__(							self	:						Union[str, Any]				,					snake_case	:						Optional[Any]				,					snake_case	:						Optional[Any]				,					snake_case	:						Optional[Any]				,					snake_case	:						List[Any]				,					snake_case	:						List[Any] = 512				,					snake_case	:						int = 512				,					snake_case	:						Union[str, Any] = 100				,					snake_case	:						str = 4.0				,					snake_case	:						Dict = 0.3				,					snake_case	:						List[str] = 1				,					snake_case	:						Optional[Any] = None				,					snake_case	:						int = "pil"				,					snake_case	:						Union[str, Any] = True				,					)		->				int:
          __UpperCAmelCase      :					Any    				=     self._execution_device

          __UpperCAmelCase      :					int    				=     guidance_scale > 1.0

          if isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ):
               __UpperCAmelCase      :					str    				=     torch.cat(__SCREAMING_SNAKE_CASE				,					dim=0     )
          if isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ):
               __UpperCAmelCase      :					Tuple    				=     torch.cat(__SCREAMING_SNAKE_CASE				,					dim=0     )
          if isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ):
               __UpperCAmelCase      :					Optional[Any]    				=     torch.cat(__SCREAMING_SNAKE_CASE				,					dim=0     )

          __UpperCAmelCase      :					List[str]    				=     image_embeds.shape[0]

          if do_classifier_free_guidance:
               __UpperCAmelCase      :					str    				=     image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE				,					dim=0     )
               __UpperCAmelCase      :					int    				=     negative_image_embeds.repeat_interleave(__SCREAMING_SNAKE_CASE				,					dim=0     )
               __UpperCAmelCase      :					str    				=     hint.repeat_interleave(__SCREAMING_SNAKE_CASE				,					dim=0     )

          __UpperCAmelCase      :					Tuple    				=     torch.cat([negative_image_embeds, image_embeds]				,					dim=0     ).to(dtype=self.unet.dtype				,					device=__SCREAMING_SNAKE_CASE     )
          __UpperCAmelCase      :					Optional[int]    				=     torch.cat([hint, hint]				,					dim=0     ).to(dtype=self.unet.dtype				,					device=__SCREAMING_SNAKE_CASE     )

          if not isinstance(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ):
               __UpperCAmelCase      :					int    				=     [image]
          if not all(isinstance(__SCREAMING_SNAKE_CASE				,					(PIL.Image.Image, torch.Tensor)     ) for i in image     ):
               raise ValueError(
                   f'Input is in incorrect format: {[type(__SCREAMING_SNAKE_CASE     ) for i in image]}. Currently, we only support  PIL image and pytorch tensor'     )

          __UpperCAmelCase      :					Union[str, Any]    				=     torch.cat([prepare_image(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     ) for i in image]				,					dim=0     )
          __UpperCAmelCase      :					Optional[int]    				=     image.to(dtype=image_embeds.dtype				,					device=__SCREAMING_SNAKE_CASE     )

          __UpperCAmelCase      :					Dict    				=     self.movq.encode(__SCREAMING_SNAKE_CASE     )['''latents''']
          __UpperCAmelCase      :					List[str]    				=     latents.repeat_interleave(__SCREAMING_SNAKE_CASE				,					dim=0     )
          self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE				,					device=__SCREAMING_SNAKE_CASE     )
          __UpperCAmelCase				,  __UpperCAmelCase      :					Union[str, Any]    				=     self.get_timesteps(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     )
          __UpperCAmelCase      :					Dict    				=     timesteps[:1].repeat(batch_size * num_images_per_prompt     )
          __UpperCAmelCase				,  __UpperCAmelCase      :					Optional[Any]    				=     downscale_height_and_width(__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					self.movq_scale_factor     )
          __UpperCAmelCase      :					Union[str, Any]    				=     self.prepare_latents(
              __SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					image_embeds.dtype				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE     )
          for i, t in enumerate(self.progress_bar(__SCREAMING_SNAKE_CASE     )     ):
               # expand the latents if we are doing classifier free guidance
               __UpperCAmelCase      :					List[Any]    				=     torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents

               __UpperCAmelCase      :					Dict    				=     {'''image_embeds''': image_embeds, '''hint''': hint}
               __UpperCAmelCase      :					List[str]    				=     self.unet(
                   sample=__SCREAMING_SNAKE_CASE				,					timestep=__SCREAMING_SNAKE_CASE				,					encoder_hidden_states=__SCREAMING_SNAKE_CASE				,					added_cond_kwargs=__SCREAMING_SNAKE_CASE				,					return_dict=__SCREAMING_SNAKE_CASE				,					)[0]

               if do_classifier_free_guidance:
                    __UpperCAmelCase				,  __UpperCAmelCase      :					Dict    				=     noise_pred.split(latents.shape[1]				,					dim=1     )
                    __UpperCAmelCase				,  __UpperCAmelCase      :					Optional[Any]    				=     noise_pred.chunk(2     )
                    __UpperCAmelCase				,  __UpperCAmelCase      :					Dict    				=     variance_pred.chunk(2     )
                    __UpperCAmelCase      :					Optional[int]    				=     noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
                    __UpperCAmelCase      :					Union[str, Any]    				=     torch.cat([noise_pred, variance_pred_text]				,					dim=1     )

               if not (
                   hasattr(self.scheduler.config				,					'''variance_type'''     )
                   and self.scheduler.config.variance_type in ["learned", "learned_range"]
               ):
                    __UpperCAmelCase				,  __UpperCAmelCase      :					str    				=     noise_pred.split(latents.shape[1]				,					dim=1     )

               # compute the previous noisy sample x_t -> x_t-1

               __UpperCAmelCase      :					int    				=     self.scheduler.step(
                   __SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					__SCREAMING_SNAKE_CASE				,					generator=__SCREAMING_SNAKE_CASE				,					)[0]

          # post-processing
          __UpperCAmelCase      :					str    				=     self.movq.decode(__SCREAMING_SNAKE_CASE				,					force_not_quantize=__SCREAMING_SNAKE_CASE     )['''sample''']

          if output_type not in ["pt", "np", "pil"]:
               raise ValueError(f'Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}'     )

          if output_type in ["np", "pil"]:
               __UpperCAmelCase      :					List[Any]    				=     image * 0.5 + 0.5
               __UpperCAmelCase      :					int    				=     image.clamp(0				,					1     )
               __UpperCAmelCase      :					Optional[Any]    				=     image.cpu().permute(0				,					2				,					3				,					1     ).float().numpy()

          if output_type == "pil":
               __UpperCAmelCase      :					List[str]    				=     self.numpy_to_pil(__SCREAMING_SNAKE_CASE     )

          if not return_dict:
               return (image,)

          return ImagePipelineOutput(images=__SCREAMING_SNAKE_CASE     )






"""simple docstring"""


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__       :  Any       		=					logging.get_logger(__name__)

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


a__       :  Optional[Any]       		=					{
    """AutoTokenizer""": """PreTrainedTokenizerBase""",
    """AutoFeatureExtractor""": """FeatureExtractionMixin""",
    """AutoImageProcessor""": """ImageProcessingMixin""",
}



class   lowercase_					(  __lowerCAmelCase				):
       snake_case__					:				Tuple									=  ["""feature_extractor""", """tokenizer"""]
       # Names need to be attr_class for attr in attributes
       snake_case__					:				Tuple									=  None
       snake_case__					:				Dict									=  None
       snake_case__					:				int									=  None

       def __init__(      self ,       *__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






        '''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(__SCREAMING_SNAKE_CASE ,       self.attributes  ):
         if attribute_name in kwargs:
          raise TypeError(F"Got multiple values for argument {attribute_name}."  )
         else:
          snake_case__     				=					arg

        if len(__SCREAMING_SNAKE_CASE  ) != len(self.attributes  ):
         raise ValueError(
             F"This processor requires {len(self.attributes  )} arguments: {', '.join(self.attributes  )}. Got "
             F"{len(__SCREAMING_SNAKE_CASE  )} 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__     				=					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__     				=					AUTO_TO_BASE_CLASS_MAPPING.get(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )
         if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
          snake_case__     				=					tuple(getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) for n in class_name if n is not None  )
         else:
          snake_case__     				=					getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

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

         setattr(self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

       def __repr__(      self  ):






        '''simple docstring'''

        snake_case__     				=					[F"- {name}: {repr(getattr(self ,       __SCREAMING_SNAKE_CASE  )  )}" for name in self.attributes]
        snake_case__     				=					"\n".join(__SCREAMING_SNAKE_CASE  )
        return F"{self.__class__.__name__}:\n{attributes_repr}"

       def 		_SCREAMING_SNAKE_CASE(      self ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE = False ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        os.makedirs(__SCREAMING_SNAKE_CASE ,       exist_ok=__SCREAMING_SNAKE_CASE  )

        if push_to_hub:
         snake_case__     				=					kwargs.pop("commit_message" ,       __SCREAMING_SNAKE_CASE  )
         snake_case__     				=					kwargs.pop("repo_id" ,       save_directory.split(os.path.sep  )[-1]  )
         snake_case__     				=					self._create_repo(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )
         snake_case__     				=					self._get_files_timestamps(__SCREAMING_SNAKE_CASE  )
        # 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__     				=					[getattr(self ,       __SCREAMING_SNAKE_CASE  ) for attribute_name in self.attributes]
         snake_case__     				=					[(a.init_kwargs if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) else a) for a in attrs]
         custom_object_save(self ,       __SCREAMING_SNAKE_CASE ,       config=__SCREAMING_SNAKE_CASE  )

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

        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__     				=					getattr(self ,       __SCREAMING_SNAKE_CASE  )
          if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
           del attribute.init_kwargs["auto_map"]

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

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE = None ,       __SCREAMING_SNAKE_CASE = False ,       __SCREAMING_SNAKE_CASE = False ,       __SCREAMING_SNAKE_CASE = None ,       __SCREAMING_SNAKE_CASE = "main" ,       **__SCREAMING_SNAKE_CASE ,       ):






        '''simple docstring'''

        snake_case__     				=					cache_dir
        snake_case__     				=					force_download
        snake_case__     				=					local_files_only
        snake_case__     				=					revision

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

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

        snake_case__     				=					cls._get_arguments_from_pretrained(__SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  )
        return cls(*__SCREAMING_SNAKE_CASE  )

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE="AutoProcessor"  ):






        '''simple docstring'''

        if not isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
         snake_case__     				=					auto_class.__name__

        import transformers.models.auto as auto_module

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

        snake_case__     				=					auto_class

       @classmethod
       def 		_SCREAMING_SNAKE_CASE(      cls ,       __SCREAMING_SNAKE_CASE ,       **__SCREAMING_SNAKE_CASE  ):






        '''simple docstring'''

        snake_case__     				=					[]
        for attribute_name in cls.attributes:
         snake_case__     				=					getattr(cls ,       F"{attribute_name}_class"  )
         if isinstance(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ):
          snake_case__     				=					tuple(getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  ) if n is not None else None for n in class_name  )
          snake_case__     				=					kwargs.get("use_fast" ,       __SCREAMING_SNAKE_CASE  )
          if use_fast and classes[1] is not None:
           snake_case__     				=					classes[1]
          else:
           snake_case__     				=					classes[0]
         else:
          snake_case__     				=					getattr(__SCREAMING_SNAKE_CASE ,       __SCREAMING_SNAKE_CASE  )

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

       @property
       def 		_SCREAMING_SNAKE_CASE(      self  ):






        '''simple docstring'''

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

