





import inspect
from typing import List, Optional, Union

import torch
from torch import nn
from torch.nn import functional as F
from torchvision import transforms
from transformers import CLIPImageProcessor, CLIPModel, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    DPMSolverMultistepScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput



class 				_lowerCAmelCase			(	nn.Module							):


  '''simple docstring'''







  def __init__(					self					:    Union[str, Any]					, UpperCamelCase					:    Tuple					, UpperCamelCase					:    Tuple=1.0							):


    '''simple docstring'''





    super().__init__()

    _snake_case      : Optional[int]														=		cut_size
    _snake_case      : Optional[int]														=		cut_power







  def UpperCamelCase_       (					self					:    Dict					, UpperCamelCase					:    List[Any]					, UpperCamelCase					:    List[str]							):


    '''simple docstring'''





    _snake_case							,    _snake_case      : Any														=		pixel_values.shape[2:4]
    _snake_case      : Any														=		min(UpperCamelCase					, UpperCamelCase							)
    _snake_case      : Tuple														=		min(UpperCamelCase					, UpperCamelCase					, self.cut_size							)
    _snake_case      : Optional[int]														=		[]
    for _ in range(UpperCamelCase							):
      _snake_case      : Dict														=		int(torch.rand([]							) ** self.cut_power * (max_size - min_size) + min_size							)
      _snake_case      : str														=		torch.randint(0					, sideX - size + 1					, ()							)
      _snake_case      : Union[str, Any]														=		torch.randint(0					, sideY - size + 1					, ()							)
      _snake_case      : Any														=		pixel_values[:, :, offsety : offsety + size, offsetx : offsetx + size]
      cutouts.append(F.adaptive_avg_poolad(UpperCamelCase					, self.cut_size							)							)
    return torch.cat(UpperCamelCase							)




def 			lowerCamelCase_		(					lowerCAmelCase:		List[Any]			,							lowerCAmelCase:		List[Any] )->						Union[str, Any]:
  _snake_case      : int														=		F.normalize(lowerCAmelCase			,							dim=-1 )
  _snake_case      : List[Any]														=		F.normalize(lowerCAmelCase			,							dim=-1 )
  return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 )


def 			lowerCamelCase_		(					lowerCAmelCase:		Any			,							lowerCAmelCase:		Dict )->						Optional[int]:
  for param in model.parameters():
    _snake_case      : Any														=		value







class 				_lowerCAmelCase			(	UpperCAmelCase_							):


  '''simple docstring'''







  def __init__(					self					:    List[Any]					, UpperCamelCase					:    AutoencoderKL					, UpperCamelCase					:    CLIPTextModel					, UpperCamelCase					:    CLIPModel					, UpperCamelCase					:    CLIPTokenizer					, UpperCamelCase					:    UNetaDConditionModel					, UpperCamelCase					:    Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler]					, UpperCamelCase					:    CLIPImageProcessor					, ):


    '''simple docstring'''





    super().__init__()
    self.register_modules(
        vae=UpperCamelCase					, text_encoder=UpperCamelCase					, clip_model=UpperCamelCase					, tokenizer=UpperCamelCase					, unet=UpperCamelCase					, scheduler=UpperCamelCase					, feature_extractor=UpperCamelCase					, )

    _snake_case      : Optional[Any]														=		transforms.Normalize(mean=feature_extractor.image_mean					, std=feature_extractor.image_std							)
    _snake_case      : Optional[Any]														=		(
        feature_extractor.size
        if isinstance(feature_extractor.size					, UpperCamelCase							)
        else feature_extractor.size['shortest_edge']
    )
    _snake_case      : Optional[int]														=		MakeCutouts(self.cut_out_size							)

    set_requires_grad(self.text_encoder					, UpperCamelCase							)
    set_requires_grad(self.clip_model					, UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Union[str, Any]					, UpperCamelCase					:    Optional[Union[str, int]] = "auto"							):


    '''simple docstring'''





    if slice_size == "auto":
      # half the attention head size is usually a good trade-off between
      # speed and memory
      _snake_case      : int														=		self.unet.config.attention_head_dim // 2
    self.unet.set_attention_slice(UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    self.enable_attention_slicing(UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    set_requires_grad(self.vae					, UpperCamelCase							)







  def UpperCamelCase_       (					self					:    List[Any]							):


    '''simple docstring'''





    set_requires_grad(self.vae					, UpperCamelCase							)







  def UpperCamelCase_       (					self					:    Optional[int]							):


    '''simple docstring'''





    set_requires_grad(self.unet					, UpperCamelCase							)







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


    '''simple docstring'''





    set_requires_grad(self.unet					, UpperCamelCase							)







  @torch.enable_grad()
  def UpperCamelCase_       (					self					:    Optional[Any]					, UpperCamelCase					:    Any					, UpperCamelCase					:    int					, UpperCamelCase					:    Tuple					, UpperCamelCase					:    Tuple					, UpperCamelCase					:    Any					, UpperCamelCase					:    Optional[Any]					, UpperCamelCase					:    List[Any]					, UpperCamelCase					:    Dict					, UpperCamelCase					:    Union[str, Any]=True					, ):


    '''simple docstring'''





    _snake_case      : Dict														=		latents.detach().requires_grad_()

    _snake_case      : List[str]														=		self.scheduler.scale_model_input(UpperCamelCase					, UpperCamelCase							)

    # predict the noise residual
    _snake_case      : Union[str, Any]														=		self.unet(UpperCamelCase					, UpperCamelCase					, encoder_hidden_states=UpperCamelCase							).sample

    if isinstance(self.scheduler					, (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler)							):
      _snake_case      : Optional[Any]														=		self.scheduler.alphas_cumprod[timestep]
      _snake_case      : int														=		1 - alpha_prod_t
      # compute predicted original sample from predicted noise also called
      # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
      _snake_case      : List[str]														=		(latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5

      _snake_case      : Union[str, Any]														=		torch.sqrt(UpperCamelCase							)
      _snake_case      : str														=		pred_original_sample * (fac) + latents * (1 - fac)
    elif isinstance(self.scheduler					, UpperCamelCase							):
      _snake_case      : int														=		self.scheduler.sigmas[index]
      _snake_case      : int														=		latents - sigma * noise_pred
    else:
      raise ValueError(f"""scheduler type {type(self.scheduler							)} not supported"""							)

    _snake_case      : Optional[Any]														=		1 / self.vae.config.scaling_factor * sample
    _snake_case      : str														=		self.vae.decode(UpperCamelCase							).sample
    _snake_case      : List[Any]														=		(image / 2 + 0.5).clamp(0					, 1							)

    if use_cutouts:
      _snake_case      : List[Any]														=		self.make_cutouts(UpperCamelCase					, UpperCamelCase							)
    else:
      _snake_case      : Optional[int]														=		transforms.Resize(self.cut_out_size							)(UpperCamelCase							)
    _snake_case      : Union[str, Any]														=		self.normalize(UpperCamelCase							).to(latents.dtype							)

    _snake_case      : Optional[int]														=		self.clip_model.get_image_features(UpperCamelCase							)
    _snake_case      : str														=		image_embeddings_clip / image_embeddings_clip.norm(p=2					, dim=-1					, keepdim=UpperCamelCase							)

    if use_cutouts:
      _snake_case      : Optional[int]														=		spherical_dist_loss(UpperCamelCase					, UpperCamelCase							)
      _snake_case      : Tuple														=		dists.view([num_cutouts, sample.shape[0], -1]							)
      _snake_case      : Optional[Any]														=		dists.sum(2							).mean(0							).sum() * clip_guidance_scale
    else:
      _snake_case      : Tuple														=		spherical_dist_loss(UpperCamelCase					, UpperCamelCase							).mean() * clip_guidance_scale

    _snake_case      : List[Any]														=		-torch.autograd.grad(UpperCamelCase					, UpperCamelCase							)[0]

    if isinstance(self.scheduler					, UpperCamelCase							):
      _snake_case      : Tuple														=		latents.detach() + grads * (sigma**2)
      _snake_case      : Tuple														=		noise_pred_original
    else:
      _snake_case      : Optional[int]														=		noise_pred_original - torch.sqrt(UpperCamelCase							) * grads
    return noise_pred, latents







  @torch.no_grad()
  def __call__(					self					:    Tuple					, UpperCamelCase					:    Union[str, List[str]]					, UpperCamelCase					:    Optional[int] = 5_12					, UpperCamelCase					:    Optional[int] = 5_12					, UpperCamelCase					:    Optional[int] = 50					, UpperCamelCase					:    Optional[float] = 7.5					, UpperCamelCase					:    Optional[int] = 1					, UpperCamelCase					:    float = 0.0					, UpperCamelCase					:    Optional[float] = 1_00					, UpperCamelCase					:    Optional[Union[str, List[str]]] = None					, UpperCamelCase					:    Optional[int] = 4					, UpperCamelCase					:    Optional[bool] = True					, UpperCamelCase					:    Optional[torch.Generator] = None					, UpperCamelCase					:    Optional[torch.FloatTensor] = None					, UpperCamelCase					:    Optional[str] = "pil"					, UpperCamelCase					:    bool = True					, ):


    '''simple docstring'''





    if isinstance(UpperCamelCase					, UpperCamelCase							):
      _snake_case      : Tuple														=		1
    elif isinstance(UpperCamelCase					, UpperCamelCase							):
      _snake_case      : List[Any]														=		len(UpperCamelCase							)
    else:
      raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(UpperCamelCase							)}"""							)

    if height % 8 != 0 or width % 8 != 0:
      raise ValueError(f"""`height` and `width` have to be divisible by 8 but are {height} and {width}."""							)

    # get prompt text embeddings
    _snake_case      : List[str]														=		self.tokenizer(
        UpperCamelCase					, padding='max_length'					, max_length=self.tokenizer.model_max_length					, truncation=UpperCamelCase					, return_tensors='pt'					, )
    _snake_case      : Union[str, Any]														=		self.text_encoder(text_input.input_ids.to(self.device							)							)[0]
    # duplicate text embeddings for each generation per prompt
    _snake_case      : str														=		text_embeddings.repeat_interleave(UpperCamelCase					, dim=0							)

    if clip_guidance_scale > 0:
      if clip_prompt is not None:
        _snake_case      : Optional[Any]														=		self.tokenizer(
            UpperCamelCase					, padding='max_length'					, max_length=self.tokenizer.model_max_length					, truncation=UpperCamelCase					, return_tensors='pt'					, ).input_ids.to(self.device							)
      else:
        _snake_case      : Dict														=		text_input.input_ids.to(self.device							)
      _snake_case      : Tuple														=		self.clip_model.get_text_features(UpperCamelCase							)
      _snake_case      : int														=		text_embeddings_clip / text_embeddings_clip.norm(p=2					, dim=-1					, keepdim=UpperCamelCase							)
      # duplicate text embeddings clip for each generation per prompt
      _snake_case      : Any														=		text_embeddings_clip.repeat_interleave(UpperCamelCase					, dim=0							)

    # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
    # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
    # corresponds to doing no classifier free guidance.
    _snake_case      : Dict														=		guidance_scale > 1.0
    # get unconditional embeddings for classifier free guidance
    if do_classifier_free_guidance:
      _snake_case      : int														=		text_input.input_ids.shape[-1]
      _snake_case      : Dict														=		self.tokenizer(['']					, padding='max_length'					, max_length=UpperCamelCase					, return_tensors='pt'							)
      _snake_case      : int														=		self.text_encoder(uncond_input.input_ids.to(self.device							)							)[0]
      # duplicate unconditional embeddings for each generation per prompt
      _snake_case      : Union[str, Any]														=		uncond_embeddings.repeat_interleave(UpperCamelCase					, dim=0							)

      # For classifier free guidance, we need to do two forward passes.
      # Here we concatenate the unconditional and text embeddings into a single batch
      # to avoid doing two forward passes
      _snake_case      : str														=		torch.cat([uncond_embeddings, text_embeddings]							)

    # get the initial random noise unless the user supplied it

    # Unlike in other pipelines, latents need to be generated in the target device
    # for 1-to-1 results reproducibility with the CompVis implementation.
    # However this currently doesn't work in `mps`.
    _snake_case      : List[Any]														=		(batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
    _snake_case      : Optional[int]														=		text_embeddings.dtype
    if latents is None:
      if self.device.type == "mps":
        # randn does not work reproducibly on mps
        _snake_case      : Any														=		torch.randn(UpperCamelCase					, generator=UpperCamelCase					, device='cpu'					, dtype=UpperCamelCase							).to(
            self.device							)
      else:
        _snake_case      : Any														=		torch.randn(UpperCamelCase					, generator=UpperCamelCase					, device=self.device					, dtype=UpperCamelCase							)
    else:
      if latents.shape != latents_shape:
        raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}"""							)
      _snake_case      : List[Any]														=		latents.to(self.device							)

    # set timesteps
    _snake_case      : Optional[Any]														=		'offset' in set(inspect.signature(self.scheduler.set_timesteps							).parameters.keys()							)
    _snake_case      : Union[str, Any]														=		{}
    if accepts_offset:
      _snake_case      : Tuple														=		1

    self.scheduler.set_timesteps(UpperCamelCase					, **UpperCamelCase							)

    # Some schedulers like PNDM have timesteps as arrays
    # It's more optimized to move all timesteps to correct device beforehand
    _snake_case      : str														=		self.scheduler.timesteps.to(self.device							)

    # scale the initial noise by the standard deviation required by the scheduler
    _snake_case      : List[str]														=		latents * self.scheduler.init_noise_sigma

    # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
    # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
    # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
    # and should be between [0, 1]
    _snake_case      : Dict														=		'eta' in set(inspect.signature(self.scheduler.step							).parameters.keys()							)
    _snake_case      : List[Any]														=		{}
    if accepts_eta:
      _snake_case      : Tuple														=		eta

    # check if the scheduler accepts generator
    _snake_case      : Any														=		'generator' in set(inspect.signature(self.scheduler.step							).parameters.keys()							)
    if accepts_generator:
      _snake_case      : str														=		generator

    for i, t in enumerate(self.progress_bar(UpperCamelCase							)							):
      # expand the latents if we are doing classifier free guidance
      _snake_case      : int														=		torch.cat([latents] * 2							) if do_classifier_free_guidance else latents
      _snake_case      : List[str]														=		self.scheduler.scale_model_input(UpperCamelCase					, UpperCamelCase							)

      # predict the noise residual
      _snake_case      : Optional[int]														=		self.unet(UpperCamelCase					, UpperCamelCase					, encoder_hidden_states=UpperCamelCase							).sample

      # perform classifier free guidance
      if do_classifier_free_guidance:
        _snake_case							,    _snake_case      : int														=		noise_pred.chunk(2							)
        _snake_case      : int														=		noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

      # perform clip guidance
      if clip_guidance_scale > 0:
        _snake_case      : str														=		(
            text_embeddings.chunk(2							)[1] if do_classifier_free_guidance else text_embeddings
        )
        _snake_case							,    _snake_case      : int														=		self.cond_fn(
            UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, )

      # compute the previous noisy sample x_t -> x_t-1
      _snake_case      : Any														=		self.scheduler.step(UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							).prev_sample

    # scale and decode the image latents with vae
    _snake_case      : Tuple														=		1 / self.vae.config.scaling_factor * latents
    _snake_case      : Optional[int]														=		self.vae.decode(UpperCamelCase							).sample

    _snake_case      : str														=		(image / 2 + 0.5).clamp(0					, 1							)
    _snake_case      : Optional[int]														=		image.cpu().permute(0					, 2					, 3					, 1							).numpy()

    if output_type == "pil":
      _snake_case      : List[Any]														=		self.numpy_to_pil(UpperCamelCase							)

    if not return_dict:
      return (image, None)

    return StableDiffusionPipelineOutput(images=UpperCamelCase					, nsfw_content_detected=UpperCamelCase							)











import importlib
import inspect
import json
import os
from collections import OrderedDict

# Build the list of all feature extractors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...feature_extraction_utils import FeatureExtractionMixin
from ...image_processing_utils import ImageProcessingMixin
from ...tokenization_utils import TOKENIZER_CONFIG_FILE
from ...utils import FEATURE_EXTRACTOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)
from .feature_extraction_auto import AutoFeatureExtractor
from .image_processing_auto import AutoImageProcessor
from .tokenization_auto import AutoTokenizer


lowerCAmelCase_        =			logging.get_logger(__name__)

lowerCAmelCase_        =			OrderedDict(
    [
        ("""align""", """AlignProcessor"""),
        ("""altclip""", """AltCLIPProcessor"""),
        ("""bark""", """BarkProcessor"""),
        ("""blip""", """BlipProcessor"""),
        ("""blip-2""", """Blip2Processor"""),
        ("""bridgetower""", """BridgeTowerProcessor"""),
        ("""chinese_clip""", """ChineseCLIPProcessor"""),
        ("""clap""", """ClapProcessor"""),
        ("""clip""", """CLIPProcessor"""),
        ("""clipseg""", """CLIPSegProcessor"""),
        ("""flava""", """FlavaProcessor"""),
        ("""git""", """GitProcessor"""),
        ("""groupvit""", """CLIPProcessor"""),
        ("""hubert""", """Wav2Vec2Processor"""),
        ("""instructblip""", """InstructBlipProcessor"""),
        ("""layoutlmv2""", """LayoutLMv2Processor"""),
        ("""layoutlmv3""", """LayoutLMv3Processor"""),
        ("""markuplm""", """MarkupLMProcessor"""),
        ("""mctct""", """MCTCTProcessor"""),
        ("""mgp-str""", """MgpstrProcessor"""),
        ("""oneformer""", """OneFormerProcessor"""),
        ("""owlvit""", """OwlViTProcessor"""),
        ("""pix2struct""", """Pix2StructProcessor"""),
        ("""sam""", """SamProcessor"""),
        ("""sew""", """Wav2Vec2Processor"""),
        ("""sew-d""", """Wav2Vec2Processor"""),
        ("""speech_to_text""", """Speech2TextProcessor"""),
        ("""speech_to_text_2""", """Speech2Text2Processor"""),
        ("""speecht5""", """SpeechT5Processor"""),
        ("""trocr""", """TrOCRProcessor"""),
        ("""tvlt""", """TvltProcessor"""),
        ("""unispeech""", """Wav2Vec2Processor"""),
        ("""unispeech-sat""", """Wav2Vec2Processor"""),
        ("""vilt""", """ViltProcessor"""),
        ("""vision-text-dual-encoder""", """VisionTextDualEncoderProcessor"""),
        ("""wav2vec2""", """Wav2Vec2Processor"""),
        ("""wav2vec2-conformer""", """Wav2Vec2Processor"""),
        ("""wavlm""", """Wav2Vec2Processor"""),
        ("""whisper""", """WhisperProcessor"""),
        ("""xclip""", """XCLIPProcessor"""),
    ]
)

lowerCAmelCase_        =			_LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)


def 			lowerCamelCase_		(					lowerCAmelCase:		str )->						Tuple:
  for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
    if class_name in processors:
      _snake_case      : Optional[Any]														=		model_type_to_module_name(lowerCAmelCase )

      _snake_case      : Tuple														=		importlib.import_module(F""".{module_name}"""			,							'transformers.models' )
      try:
        return getattr(lowerCAmelCase			,							lowerCAmelCase )
      except AttributeError:
        continue

  for processor in PROCESSOR_MAPPING._extra_content.values():
    if getattr(lowerCAmelCase			,							'__name__'			,							lowerCAmelCase ) == class_name:
      return processor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
  _snake_case      : Union[str, Any]														=		importlib.import_module('transformers' )
  if hasattr(lowerCAmelCase			,							lowerCAmelCase ):
    return getattr(lowerCAmelCase			,							lowerCAmelCase )

  return None







class 				_lowerCAmelCase			:


  '''simple docstring'''







  def __init__(					self					:    Optional[Any]							):


    '''simple docstring'''





    raise EnvironmentError(
        'AutoProcessor is designed to be instantiated '
        'using the `AutoProcessor.from_pretrained(pretrained_model_name_or_path)` method.'							)







  @classmethod
  @replace_list_option_in_docstrings(UpperCamelCase							)
  def UpperCamelCase_       (					cls					:    Optional[Any]					, UpperCamelCase					:    Optional[Any]					, **UpperCamelCase					:    Dict							):


    '''simple docstring'''





    _snake_case      : Optional[int]														=		kwargs.pop('config'					, UpperCamelCase							)
    _snake_case      : str														=		kwargs.pop('trust_remote_code'					, UpperCamelCase							)
    _snake_case      : List[Any]														=		True

    _snake_case      : str														=		None
    _snake_case      : str														=		None

    # First, let's see if we have a preprocessor config.
    # Filter the kwargs for `get_file_from_repo`.
    _snake_case      : Dict														=		{
        key: kwargs[key] for key in inspect.signature(UpperCamelCase							).parameters.keys() if key in kwargs
    }
    # Let's start by checking whether the processor class is saved in an image processor
    _snake_case      : List[Any]														=		get_file_from_repo(
        UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
    if preprocessor_config_file is not None:
      _snake_case							,    _snake_case      : Optional[int]														=		ImageProcessingMixin.get_image_processor_dict(UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : List[str]														=		config_dict.get('processor_class'					, UpperCamelCase							)
      if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
        _snake_case      : Optional[Any]														=		config_dict['auto_map']['AutoProcessor']

        # If not found, let's check whether the processor class is saved in a feature extractor config
    if preprocessor_config_file is not None and processor_class is None:
      _snake_case							,    _snake_case      : Union[str, Any]														=		FeatureExtractionMixin.get_feature_extractor_dict(UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : int														=		config_dict.get('processor_class'					, UpperCamelCase							)
      if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
        _snake_case      : str														=		config_dict['auto_map']['AutoProcessor']

    if processor_class is None:
      # Next, let's check whether the processor class is saved in a tokenizer
      _snake_case      : Union[str, Any]														=		get_file_from_repo(
          UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
      if tokenizer_config_file is not None:
        with open(UpperCamelCase					, encoding='utf-8'							) as reader:
          _snake_case      : Optional[int]														=		json.load(UpperCamelCase							)

        _snake_case      : int														=		config_dict.get('processor_class'					, UpperCamelCase							)
        if "AutoProcessor" in config_dict.get('auto_map'					, {}							):
          _snake_case      : str														=		config_dict['auto_map']['AutoProcessor']

    if processor_class is None:
      # Otherwise, load config, if it can be loaded.
      if not isinstance(UpperCamelCase					, UpperCamelCase							):
        _snake_case      : Dict														=		AutoConfig.from_pretrained(
            UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)

      # And check if the config contains the processor class.
      _snake_case      : str														=		getattr(UpperCamelCase					, 'processor_class'					, UpperCamelCase							)
      if hasattr(UpperCamelCase					, 'auto_map'							) and "AutoProcessor" in config.auto_map:
        _snake_case      : Any														=		config.auto_map['AutoProcessor']

    if processor_class is not None:
      _snake_case      : Tuple														=		processor_class_from_name(UpperCamelCase							)

    _snake_case      : int														=		processor_auto_map is not None
    _snake_case      : Optional[int]														=		processor_class is not None or type(UpperCamelCase							) in PROCESSOR_MAPPING
    _snake_case      : Union[str, Any]														=		resolve_trust_remote_code(
        UpperCamelCase					, UpperCamelCase					, UpperCamelCase					, UpperCamelCase							)

    if has_remote_code and trust_remote_code:
      _snake_case      : List[str]														=		get_class_from_dynamic_module(
          UpperCamelCase					, UpperCamelCase					, **UpperCamelCase							)
      _snake_case      : Optional[Any]														=		kwargs.pop('code_revision'					, UpperCamelCase							)
      if os.path.isdir(UpperCamelCase							):
        processor_class.register_for_auto_class()
      return processor_class.from_pretrained(
          UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)
    elif processor_class is not None:
      return processor_class.from_pretrained(
          UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)
    # Last try: we use the PROCESSOR_MAPPING.
    elif type(UpperCamelCase							) in PROCESSOR_MAPPING:
      return PROCESSOR_MAPPING[type(UpperCamelCase							)].from_pretrained(UpperCamelCase					, **UpperCamelCase							)

    # At this stage, there doesn't seem to be a `Processor` class available for this model, so let's try a
    # tokenizer.
    try:
      return AutoTokenizer.from_pretrained(
          UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)
    except Exception:
      try:
        return AutoImageProcessor.from_pretrained(
            UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)
      except Exception:
        pass

      try:
        return AutoFeatureExtractor.from_pretrained(
            UpperCamelCase					, trust_remote_code=UpperCamelCase					, **UpperCamelCase							)
      except Exception:
        pass

    raise ValueError(
        f"""Unrecognized processing class in {pretrained_model_name_or_path}. Can't instantiate a processor, a """
        'tokenizer, an image processor or a feature extractor for this model. Make sure the repository contains'
        'the files of at least one of those processing classes.'							)







  @staticmethod
  def UpperCamelCase_       (					UpperCamelCase					:    int					, UpperCamelCase					:    str							):


    '''simple docstring'''





    PROCESSOR_MAPPING.register(UpperCamelCase					, UpperCamelCase							)




