



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


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


def  __SCREAMING_SNAKE_CASE (  self   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      ):
		_lowercase				: Optional[Any]     =   image.to(device=__UpperCAmelCase      )
		_lowercase				: List[str]     =   image  # take image as image_embeddings
		_lowercase				: str     =   image_embeddings.unsqueeze(1      )

		# duplicate image embeddings for each generation per prompt, using mps friendly method
		_lowercase     ,  _lowercase     ,  _lowercase				: Any     =   image_embeddings.shape
		_lowercase				: Optional[int]     =   image_embeddings.repeat(1   ,				__UpperCAmelCase   ,				1      )
		_lowercase				: Any     =   image_embeddings.view(bs_embed * num_images_per_prompt   ,				__UpperCAmelCase   ,				-1      )

		if do_classifier_free_guidance:
				_lowercase				: List[Any]     =   torch.zeros_like(__UpperCAmelCase      )

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

		return image_embeddings





class   UpperCamelCase	(     snake_case       ):




	"""simple docstring"""






	def __init__(     self				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_ = None				,):
			super().__init__()

			_lowercase				: str     =   {"""image_encoder""": None} if decoder_pipe_kwargs is None else decoder_pipe_kwargs

			_lowercase				: List[Any]     =   decoder_pipe_kwargs.get("""torch_dtype"""				,UpperCAmelCase_   ) or prior.dtype

			_lowercase				: List[Any]     =   StableDiffusionImageVariationPipeline.from_pretrained(
			    """lambdalabs/sd-image-variations-diffusers"""				,**UpperCAmelCase_   )

			# replace `_encode_image` method
			_lowercase				: Optional[Any]     =   types.MethodType(_encode_image				,self.decoder_pipe   )

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






	def    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,):
			if text_model_output is None:
					_lowercase				: Tuple     =   len(UpperCAmelCase_   ) if isinstance(UpperCAmelCase_				,UpperCAmelCase_   ) else 1
					# get prompt text embeddings
					_lowercase				: List[str]     =   self.tokenizer(
					    UpperCAmelCase_				,padding="""max_length"""				,max_length=self.tokenizer.model_max_length				,return_tensors="""pt"""				,)
					_lowercase				: str     =   text_inputs.input_ids
					_lowercase				: int     =   text_inputs.attention_mask.bool().to(UpperCAmelCase_   )

					if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
							_lowercase				: Optional[Any]     =   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}"""   )
							_lowercase				: str     =   text_input_ids[:, : self.tokenizer.model_max_length]

					_lowercase				: int     =   self.text_encoder(text_input_ids.to(UpperCAmelCase_   )   )

					_lowercase				: Optional[Any]     =   text_encoder_output.text_embeds
					_lowercase				: Any     =   text_encoder_output.last_hidden_state

			else:
					_lowercase				: Tuple     =   text_model_output[0].shape[0]
					_lowercase     ,  _lowercase				: Dict     =   text_model_output[0], text_model_output[1]
					_lowercase				: str     =   text_attention_mask

			_lowercase				: Tuple     =   text_embeddings.repeat_interleave(UpperCAmelCase_				,dim=0   )
			_lowercase				: str     =   text_encoder_hidden_states.repeat_interleave(UpperCAmelCase_				,dim=0   )
			_lowercase				: Tuple     =   text_mask.repeat_interleave(UpperCAmelCase_				,dim=0   )

			if do_classifier_free_guidance:
					_lowercase				: Optional[Any]     =   [""""""] * batch_size

					_lowercase				: Dict     =   self.tokenizer(
					    UpperCAmelCase_				,padding="""max_length"""				,max_length=self.tokenizer.model_max_length				,truncation=UpperCAmelCase_				,return_tensors="""pt"""				,)
					_lowercase				: Optional[Any]     =   uncond_input.attention_mask.bool().to(UpperCAmelCase_   )
					_lowercase				: List[str]     =   self.text_encoder(uncond_input.input_ids.to(UpperCAmelCase_   )   )

					_lowercase				: str     =   uncond_embeddings_text_encoder_output.text_embeds
					_lowercase				: Any     =   uncond_embeddings_text_encoder_output.last_hidden_state

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

					_lowercase				: Union[str, Any]     =   uncond_embeddings.shape[1]
					_lowercase				: Dict     =   uncond_embeddings.repeat(1				,UpperCAmelCase_   )
					_lowercase				: int     =   uncond_embeddings.view(batch_size * num_images_per_prompt				,UpperCAmelCase_   )

					_lowercase				: Dict     =   uncond_text_encoder_hidden_states.shape[1]
					_lowercase				: Tuple     =   uncond_text_encoder_hidden_states.repeat(1				,UpperCAmelCase_				,1   )
					_lowercase				: Tuple     =   uncond_text_encoder_hidden_states.view(
					    batch_size * num_images_per_prompt				,UpperCAmelCase_				,-1   )
					_lowercase				: List[Any]     =   uncond_text_mask.repeat_interleave(UpperCAmelCase_				,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
					_lowercase				: Any     =   torch.cat([uncond_embeddings, text_embeddings]   )
					_lowercase				: Tuple     =   torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states]   )

					_lowercase				: Union[str, Any]     =   torch.cat([uncond_text_mask, text_mask]   )

			return text_embeddings, text_encoder_hidden_states, text_mask






	@property
	def    lowerCamelCase__					(     self   ):
			if self.device != torch.device("""meta"""   ) or not hasattr(self.prior				,"""_hf_hook"""   ):
					return self.device
			for module in self.prior.modules():
					if (
					    hasattr(UpperCAmelCase_				,"""_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    lowerCamelCase__					(     self				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_   ):
			if latents is None:
					_lowercase				: Optional[Any]     =   randn_tensor(UpperCAmelCase_				,generator=UpperCAmelCase_				,device=UpperCAmelCase_				,dtype=UpperCAmelCase_   )
			else:
					if latents.shape != shape:
							raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}"""   )
					_lowercase				: Optional[Any]     =   latents.to(UpperCAmelCase_   )

			_lowercase				: Optional[Any]     =   latents * scheduler.init_noise_sigma
			return latents






	def    lowerCamelCase__					(     self				,UpperCAmelCase_ = None   ):
			self.decoder_pipe.to(UpperCAmelCase_   )
			super().to(UpperCAmelCase_   )






	@torch.no_grad()
	def __call__(     self				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = 1				,UpperCAmelCase_ = 25				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = None				,UpperCAmelCase_ = 4.0				,UpperCAmelCase_ = 8.0				,UpperCAmelCase_ = 50				,UpperCAmelCase_ = 1				,UpperCAmelCase_ = 0.0				,UpperCAmelCase_ = "pil"				,UpperCAmelCase_ = True				,):
			if prompt is not None:
					if isinstance(UpperCAmelCase_				,UpperCAmelCase_   ):
							_lowercase				: Optional[Any]     =   1
					elif isinstance(UpperCAmelCase_				,UpperCAmelCase_   ):
							_lowercase				: Union[str, Any]     =   len(UpperCAmelCase_   )
					else:
							raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_   )}"""   )
			else:
					_lowercase				: List[str]     =   text_model_output[0].shape[0]

			_lowercase				: List[str]     =   self._execution_device

			_lowercase				: str     =   batch_size * num_images_per_prompt

			_lowercase				: List[Any]     =   prior_guidance_scale > 1.0 or decoder_guidance_scale > 1.0

			_lowercase     ,  _lowercase     ,  _lowercase				: List[Any]     =   self._encode_prompt(
			    UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_   )

			# prior

			self.prior_scheduler.set_timesteps(UpperCAmelCase_				,device=UpperCAmelCase_   )
			_lowercase				: List[Any]     =   self.prior_scheduler.timesteps

			_lowercase				: Union[str, Any]     =   self.prior.config.embedding_dim

			_lowercase				: Tuple     =   self.prepare_latents(
			    (batch_size, embedding_dim)				,text_embeddings.dtype				,UpperCAmelCase_				,UpperCAmelCase_				,UpperCAmelCase_				,self.prior_scheduler				,)

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

					_lowercase				: Union[str, Any]     =   self.prior(
					    UpperCAmelCase_				,timestep=UpperCAmelCase_				,proj_embedding=UpperCAmelCase_				,encoder_hidden_states=UpperCAmelCase_				,attention_mask=UpperCAmelCase_				,).predicted_image_embedding

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

					if i + 1 == prior_timesteps_tensor.shape[0]:
							_lowercase				: List[Any]     =   None
					else:
							_lowercase				: str     =   prior_timesteps_tensor[i + 1]

					_lowercase				: Optional[Any]     =   self.prior_scheduler.step(
					    UpperCAmelCase_				,timestep=UpperCAmelCase_				,sample=UpperCAmelCase_				,generator=UpperCAmelCase_				,prev_timestep=UpperCAmelCase_				,).prev_sample

			_lowercase				: int     =   self.prior.post_process_latents(UpperCAmelCase_   )

			_lowercase				: Union[str, Any]     =   prior_latents

			_lowercase				: Union[str, Any]     =   self.decoder_pipe(
			    image=UpperCAmelCase_				,height=UpperCAmelCase_				,width=UpperCAmelCase_				,num_inference_steps=UpperCAmelCase_				,guidance_scale=UpperCAmelCase_				,generator=UpperCAmelCase_				,output_type=UpperCAmelCase_				,return_dict=UpperCAmelCase_				,num_images_per_prompt=UpperCAmelCase_				,eta=UpperCAmelCase_				,)
			return output










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

