


"""simple docstring"""


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


a_											=     logging.get_logger(__name__)

a_											=     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"),
    ]
)

a_											=     _LazyAutoMapping(CONFIG_MAPPING_NAMES, PROCESSOR_MAPPING_NAMES)






def   a__			(					__lowercase )						->						Union[str, Any]:
				for module_name, processors in PROCESSOR_MAPPING_NAMES.items():
								if class_name in processors:
												_A       	=      model_type_to_module_name(__lowercase )

												_A       	=      importlib.import_module(f""".{module_name}"""  ,      "transformers.models" )
												try:
																return getattr(__lowercase  ,      __lowercase )
												except AttributeError:
																continue

				for processor in PROCESSOR_MAPPING._extra_content.values():
								if getattr(__lowercase  ,      "__name__"  ,      __lowercase ) == 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.
				_A       	=      importlib.import_module("transformers" )
				if hasattr(__lowercase  ,      __lowercase ):
								return getattr(__lowercase  ,      __lowercase )

				return None




class snake_case   :







		def __init__(       self   :							str		)							->    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(a__		)
		def 			a_			(       cls   :							Optional[Any]     , a__   :							Tuple     , **a__   :							List[str]		)							->    Dict:





						'''simple docstring'''







						_A       	=      kwargs.pop("config"     , a__		)
						_A       	=      kwargs.pop("trust_remote_code"     , a__		)
						_A       	=      True

						_A       	=      None
						_A       	=      None

						# First, let's see if we have a preprocessor config.
						# Filter the kwargs for `get_file_from_repo`.
						_A       	=      {
						    key: kwargs[key] for key in inspect.signature(a__		).parameters.keys() if key in kwargs
						}
						# Let's start by checking whether the processor class is saved in an image processor
						_A       	=      get_file_from_repo(
						    a__     , a__     , **a__		)
						if preprocessor_config_file is not None:
										_A	,		_A       	=      ImageProcessingMixin.get_image_processor_dict(a__     , **a__		)
										_A       	=      config_dict.get("processor_class"     , a__		)
										if "AutoProcessor" in config_dict.get("auto_map"     , {}		):
														_A       	=      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:
										_A	,		_A       	=      FeatureExtractionMixin.get_feature_extractor_dict(a__     , **a__		)
										_A       	=      config_dict.get("processor_class"     , a__		)
										if "AutoProcessor" in config_dict.get("auto_map"     , {}		):
														_A       	=      config_dict["auto_map"]["AutoProcessor"]

						if processor_class is None:
										# Next, let's check whether the processor class is saved in a tokenizer
										_A       	=      get_file_from_repo(
										    a__     , a__     , **a__		)
										if tokenizer_config_file is not None:
														with open(a__     , encoding="utf-8"		) as reader:
																		_A       	=      json.load(a__		)

														_A       	=      config_dict.get("processor_class"     , a__		)
														if "AutoProcessor" in config_dict.get("auto_map"     , {}		):
																		_A       	=      config_dict["auto_map"]["AutoProcessor"]

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

										# And check if the config contains the processor class.
										_A       	=      getattr(a__     , "processor_class"     , a__		)
										if hasattr(a__     , "auto_map"		) and "AutoProcessor" in config.auto_map:
														_A       	=      config.auto_map["AutoProcessor"]

						if processor_class is not None:
										_A       	=      processor_class_from_name(a__		)

						_A       	=      processor_auto_map is not None
						_A       	=      processor_class is not None or type(a__		) in PROCESSOR_MAPPING
						_A       	=      resolve_trust_remote_code(
						    a__     , a__     , a__     , a__		)

						if has_remote_code and trust_remote_code:
										_A       	=      get_class_from_dynamic_module(
										    a__     , a__     , **a__		)
										_A       	=      kwargs.pop("code_revision"     , a__		)
										if os.path.isdir(a__		):
														processor_class.register_for_auto_class()
										return processor_class.from_pretrained(
										    a__     , trust_remote_code=a__     , **a__		)
						elif processor_class is not None:
										return processor_class.from_pretrained(
										    a__     , trust_remote_code=a__     , **a__		)
						# Last try: we use the PROCESSOR_MAPPING.
						elif type(a__		) in PROCESSOR_MAPPING:
										return PROCESSOR_MAPPING[type(a__		)].from_pretrained(a__     , **a__		)

						# 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(
										    a__     , trust_remote_code=a__     , **a__		)
						except Exception:
										try:
														return AutoImageProcessor.from_pretrained(
														    a__     , trust_remote_code=a__     , **a__		)
										except Exception:
														pass

										try:
														return AutoFeatureExtractor.from_pretrained(
														    a__     , trust_remote_code=a__     , **a__		)
										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 			a_			(       a__   :							Optional[int]     , a__   :							str		)							->    Union[str, Any]:





						'''simple docstring'''







						PROCESSOR_MAPPING.register(a__     , a__		)



"""simple docstring"""


import types
from typing import List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer
from transformers.models.clip.modeling_clip import CLIPTextModelOutput

from diffusers.models import PriorTransformer
from diffusers.pipelines import DiffusionPipeline, StableDiffusionImageVariationPipeline
from diffusers.schedulers import UnCLIPScheduler
from diffusers.utils import logging, randn_tensor


a_											=     logging.get_logger(__name__)  # pylint: disable=invalid-name






def   a__			(					self  ,      __lowercase  ,      __lowercase  ,      __lowercase  ,      __lowercase )						->						Tuple:
				_A       	=      image.to(device=__lowercase )
				_A       	=      image  # take image as image_embeddings
				_A       	=      image_embeddings.unsqueeze(1 )

				# duplicate image embeddings for each generation per prompt, using mps friendly method
				_A	,		_A	,		_A       	=      image_embeddings.shape
				_A       	=      image_embeddings.repeat(1  ,      __lowercase  ,      1 )
				_A       	=      image_embeddings.view(bs_embed * num_images_per_prompt  ,      __lowercase  ,      -1 )

				if do_classifier_free_guidance:
								_A       	=      torch.zeros_like(__lowercase )

								# 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
								_A       	=      torch.cat([uncond_embeddings, image_embeddings] )

				return image_embeddings




class snake_case   (	_UpperCamelCase):







		def __init__(       self   :							Dict     , a__   :							PriorTransformer     , a__   :							CLIPTokenizer     , a__   :							CLIPTextModelWithProjection     , a__   :							UnCLIPScheduler     , a__   :							Optional[dict] = None     , )							->    Optional[Any]:





						'''simple docstring'''







						super().__init__()

						_A       	=      {"image_encoder": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

						_A       	=      decoder_pipe_kwargs.get("torch_dtype"     , a__		) or prior.dtype

						_A       	=      StableDiffusionImageVariationPipeline.from_pretrained(
						    "lambdalabs/sd-image-variations-diffusers"     , **a__		)

						# replace `_encode_image` method
						_A       	=      types.MethodType(_encode_image     , self.decoder_pipe		)

						self.register_modules(
						    prior=a__     , tokenizer=a__     , text_encoder=a__     , prior_scheduler=a__     , )







		def 			a_			(       self   :							Optional[Any]     , a__   :							str     , a__   :							Optional[Any]     , a__   :							int     , a__   :							Optional[int]     , a__   :							Optional[Union[CLIPTextModelOutput, Tuple]] = None     , a__   :							Optional[torch.Tensor] = None     , )							->    Optional[Any]:





						'''simple docstring'''







						if text_model_output is None:
										_A       	=      len(a__		) if isinstance(a__     , a__		) else 1
										# get prompt text embeddings
										_A       	=      self.tokenizer(
										    a__     , padding="max_length"     , max_length=self.tokenizer.model_max_length     , return_tensors="pt"     , )
										_A       	=      text_inputs.input_ids
										_A       	=      text_inputs.attention_mask.bool().to(a__		)

										if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
														_A       	=      self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :]		)
														logger.warning(
														    "The following part of your input was truncated because CLIP can only handle sequences up to"
														    F""" {self.tokenizer.model_max_length} tokens: {removed_text}"""		)
														_A       	=      text_input_ids[:, : self.tokenizer.model_max_length]

										_A       	=      self.text_encoder(text_input_ids.to(a__		)		)

										_A       	=      text_encoder_output.text_embeds
										_A       	=      text_encoder_output.last_hidden_state

						else:
										_A       	=      text_model_output[0].shape[0]
										_A	,		_A       	=      text_model_output[0], text_model_output[1]
										_A       	=      text_attention_mask

						_A       	=      text_embeddings.repeat_interleave(a__     , dim=0		)
						_A       	=      text_encoder_hidden_states.repeat_interleave(a__     , dim=0		)
						_A       	=      text_mask.repeat_interleave(a__     , dim=0		)

						if do_classifier_free_guidance:
										_A       	=      [""] * batch_size

										_A       	=      self.tokenizer(
										    a__     , padding="max_length"     , max_length=self.tokenizer.model_max_length     , truncation=a__     , return_tensors="pt"     , )
										_A       	=      uncond_input.attention_mask.bool().to(a__		)
										_A       	=      self.text_encoder(uncond_input.input_ids.to(a__		)		)

										_A       	=      uncond_embeddings_text_encoder_output.text_embeds
										_A       	=      uncond_embeddings_text_encoder_output.last_hidden_state

										# duplicate unconditional embeddings for each generation per prompt, using mps friendly method

										_A       	=      uncond_embeddings.shape[1]
										_A       	=      uncond_embeddings.repeat(1     , a__		)
										_A       	=      uncond_embeddings.view(batch_size * num_images_per_prompt     , a__		)

										_A       	=      uncond_text_encoder_hidden_states.shape[1]
										_A       	=      uncond_text_encoder_hidden_states.repeat(1     , a__     , 1		)
										_A       	=      uncond_text_encoder_hidden_states.view(
										    batch_size * num_images_per_prompt     , a__     , -1		)
										_A       	=      uncond_text_mask.repeat_interleave(a__     , dim=0		)

										# done duplicates

										# 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
										_A       	=      torch.cat([uncond_embeddings, text_embeddings]		)
										_A       	=      torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]		)

										_A       	=      torch.cat([uncond_text_mask, text_mask]		)

						return text_embeddings, text_encoder_hidden_states, text_mask







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





						'''simple docstring'''







						if self.device != torch.device("meta"		) or not hasattr(self.prior     , "_hf_hook"		):
										return self.device
						for module in self.prior.modules():
										if (
										    hasattr(a__     , "_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







		def 			a_			(       self   :							str     , a__   :							int     , a__   :							str     , a__   :							List[str]     , a__   :							Dict     , a__   :							Optional[Any]     , a__   :							Dict		)							->    int:





						'''simple docstring'''







						if latents is None:
										_A       	=      randn_tensor(a__     , generator=a__     , device=a__     , dtype=a__		)
						else:
										if latents.shape != shape:
														raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}"""		)
										_A       	=      latents.to(a__		)

						_A       	=      latents * scheduler.init_noise_sigma
						return latents







		def 			a_			(       self   :							List[str]     , a__   :							Optional[Union[str, torch.device]] = None		)							->    Any:





						'''simple docstring'''







						self.decoder_pipe.to(a__		)
						super().to(a__		)







		@torch.no_grad()
		def __call__(       self   :							List[Any]     , a__   :							Optional[Union[str, List[str]]] = None     , a__   :							Optional[int] = None     , a__   :							Optional[int] = None     , a__   :							int = 1     , a__   :							int = 25     , a__   :							Optional[torch.Generator] = None     , a__   :							Optional[torch.FloatTensor] = None     , a__   :							Optional[Union[CLIPTextModelOutput, Tuple]] = None     , a__   :							Optional[torch.Tensor] = None     , a__   :							float = 4.0     , a__   :							float = 8.0     , a__   :							int = 50     , a__   :							Optional[int] = 1     , a__   :							float = 0.0     , a__   :							Optional[str] = "pil"     , a__   :							bool = True     , )							->    str:





						'''simple docstring'''







						if prompt is not None:
										if isinstance(a__     , a__		):
														_A       	=      1
										elif isinstance(a__     , a__		):
														_A       	=      len(a__		)
										else:
														raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(a__		)}"""		)
						else:
										_A       	=      text_model_output[0].shape[0]

						_A       	=      self._execution_device

						_A       	=      batch_size * num_images_per_prompt

						_A       	=      prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

						_A	,		_A	,		_A       	=      self._encode_prompt(
						    a__     , a__     , a__     , a__     , a__     , a__		)

						# prior

						self.prior_scheduler.set_timesteps(a__     , device=a__		)
						_A       	=      self.prior_scheduler.timesteps

						_A       	=      self.prior.config.embedding_dim

						_A       	=      self.prepare_latents(
						    (batch_size, embedding_dim)     , text_embeddings.dtype     , a__     , a__     , a__     , self.prior_scheduler     , )

						for i, t in enumerate(self.progress_bar(a__		)		):
										# expand the latents if we are doing classifier free guidance
										_A       	=      torch.cat([prior_latents] * 2		) if do_classifier_free_guidance else prior_latents

										_A       	=      self.prior(
										    a__     , timestep=a__     , proj_embedding=a__     , encoder_hidden_states=a__     , attention_mask=a__     , ).predicted_image_embedding

										if do_classifier_free_guidance:
														_A	,		_A       	=      predicted_image_embedding.chunk(2		)
														_A       	=      predicted_image_embedding_uncond + prior_guidance_scale * (
														    predicted_image_embedding_text - predicted_image_embedding_uncond
														)

										if i + 1 == prior_timesteps_tensor.shape[0]:
														_A       	=      None
										else:
														_A       	=      prior_timesteps_tensor[i + 1]

										_A       	=      self.prior_scheduler.step(
										    a__     , timestep=a__     , sample=a__     , generator=a__     , prev_timestep=a__     , ).prev_sample

						_A       	=      self.prior.post_process_latents(a__		)

						_A       	=      prior_latents

						_A       	=      self.decoder_pipe(
						    image=a__     , height=a__     , width=a__     , num_inference_steps=a__     , guidance_scale=a__     , generator=a__     , output_type=a__     , return_dict=a__     , num_images_per_prompt=a__     , eta=a__     , )
						return output