





"""simple docstring"""





import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
       from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
       from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      return 1.0 / (1.0 + np.exp(-_outputs			))


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Dict			):







      '''simple docstring'''




      lowerCAmelCase  						=       np.max(_outputs							,						axis=-1							,						keepdims=SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       np.exp(_outputs - maxes			)
      return shifted_exp / shifted_exp.sum(axis=-1							,						keepdims=SCREAMING_SNAKE_CASE			)

class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      'sigmoid'
      _SCREAMING_SNAKE_CASE					=      'softmax'
      _SCREAMING_SNAKE_CASE					=      'none'







@add_end_docstrings(
    _UpperCAmelCase     ,  r'\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `"default"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `"sigmoid"`: Applies the sigmoid function on the output.\n            - `"softmax"`: Applies the softmax function on the output.\n            - `"none"`: Does not apply any function on the output.\n    '     ,  )
class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      False
      _SCREAMING_SNAKE_CASE					=      ClassificationFunction.NONE





      def __init__(       self      ,						**lowercase )		->     Tuple:
            super().__init__(**lowercase )

            self.check_model_type(
                TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
                if self.framework == """tf"""
                else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING )





      def     _snake_case			(       self      ,						lowercase=None      ,						lowercase=None      ,						lowercase=""      ,						**lowercase )		->     Dict:
            # Using "" as default argument because we're going to use `top_k=None` in user code to declare
            # "No top_k"
            lowerCAmelCase  						=       tokenizer_kwargs

            lowerCAmelCase  						=       {}
            if hasattr(self.model.config      ,						"""return_all_scores""" ) and return_all_scores is None:
                  lowerCAmelCase  						=       self.model.config.return_all_scores

            if isinstance(lowercase      ,						lowercase ) or top_k is None:
                  lowerCAmelCase  						=       top_k
                  lowerCAmelCase  						=       False
            elif return_all_scores is not None:
                  warnings.warn(
                      """`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"""
                      """ `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."""      ,						lowercase      ,						)
                  if return_all_scores:
                        lowerCAmelCase  						=       None
                  else:
                        lowerCAmelCase  						=       1

            if isinstance(lowercase      ,						lowercase ):
                  lowerCAmelCase  						=       ClassificationFunction[function_to_apply.upper()]

            if function_to_apply is not None:
                  lowerCAmelCase  						=       function_to_apply
            return preprocess_params, {}, postprocess_params





      def __call__(       self      ,						*lowercase      ,						**lowercase )		->     int:
            lowerCAmelCase  						=       super().__call__(*lowercase      ,						**lowercase )
            # TODO try and retrieve it in a nicer way from _sanitize_parameters.
            lowerCAmelCase  						=       """top_k""" not in kwargs
            if isinstance(args[0]      ,						lowercase ) and _legacy:
                  # This pipeline is odd, and return a list when single item is run
                  return [result]
            else:
                  return result





      def     _snake_case			(       self      ,						lowercase      ,						**lowercase )		->     Dict[str, GenericTensor]:
            lowerCAmelCase  						=       self.framework
            if isinstance(lowercase      ,						lowercase ):
                  return self.tokenizer(**lowercase      ,						return_tensors=lowercase      ,						**lowercase )
            elif isinstance(lowercase      ,						lowercase ) and len(lowercase ) == 1 and isinstance(inputs[0]      ,						lowercase ) and len(inputs[0] ) == 2:
                  # It used to be valid to use a list of list of list for text pairs, keeping this path for BC
                  return self.tokenizer(
                      text=inputs[0][0]      ,						text_pair=inputs[0][1]      ,						return_tensors=lowercase      ,						**lowercase )
            elif isinstance(lowercase      ,						lowercase ):
                  # This is likely an invalid usage of the pipeline attempting to pass text pairs.
                  raise ValueError(
                      """The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"""
                      """ dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair.""" )
            return self.tokenizer(lowercase      ,						return_tensors=lowercase      ,						**lowercase )





      def     _snake_case			(       self      ,						lowercase )		->     Optional[Any]:
            return self.model(**lowercase )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase=None      ,						lowercase=1      ,						lowercase=True )		->     Optional[int]:
            # `_legacy` is used to determine if we're running the naked pipeline and in backward
            # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
            # the more natural result containing the list.
            # Default value before `set_parameters`
            if function_to_apply is None:
                  if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                        lowerCAmelCase  						=       ClassificationFunction.SIGMOID
                  elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                        lowerCAmelCase  						=       ClassificationFunction.SOFTMAX
                  elif hasattr(self.model.config      ,						"""function_to_apply""" ) and function_to_apply is None:
                        lowerCAmelCase  						=       self.model.config.function_to_apply
                  else:
                        lowerCAmelCase  						=       ClassificationFunction.NONE

            lowerCAmelCase  						=       model_outputs["""logits"""][0]
            lowerCAmelCase  						=       outputs.numpy()

            if function_to_apply == ClassificationFunction.SIGMOID:
                  lowerCAmelCase  						=       sigmoid(lowercase )
            elif function_to_apply == ClassificationFunction.SOFTMAX:
                  lowerCAmelCase  						=       softmax(lowercase )
            elif function_to_apply == ClassificationFunction.NONE:
                  lowerCAmelCase  						=       outputs
            else:
                  raise ValueError(f'Unrecognized `function_to_apply` argument: {function_to_apply}' )

            if top_k == 1 and _legacy:
                  return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

            lowerCAmelCase  						=       [
                {"""label""": self.model.config.idalabel[i], """score""": score.item()} for i, score in enumerate(lowercase )
            ]
            if not _legacy:
                  dict_scores.sort(key=lambda lowercase : x["score"]      ,						reverse=lowercase )
                  if top_k is not None:
                        lowerCAmelCase  						=       dict_scores[:top_k]
            return dict_scores













import os
from glob import glob

import imageio
import torch
import torchvision
import wandb
from img_processing import custom_to_pil, loop_post_process, preprocess, preprocess_vqgan
from loaders import load_vqgan
from PIL import Image
from torch import nn

from transformers import CLIPModel, CLIPTokenizerFast
from utils import get_device, get_timestamp, show_pil






class     lowercase__       :

   '''simple docstring'''


   def __init__(    self,		__magic_name__ = "cpu",		__magic_name__ = "openai/clip-vit-large-patch14"							) ->      None:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      device
       UpperCamelCase__							:				Union[str, Any]          =      CLIPTokenizerFast.from_pretrained(__magic_name__							)
       UpperCamelCase__							:				Tuple          =      [0.4814_5466, 0.457_8275, 0.4082_1073]
       UpperCamelCase__							:				Union[str, Any]          =      [0.2686_2954, 0.2613_0258, 0.2757_7711]
       UpperCamelCase__							:				Dict          =      torchvision.transforms.Normalize(self.image_mean,		self.image_std							)
       UpperCamelCase__							:				List[str]          =      torchvision.transforms.Resize(224							)
       UpperCamelCase__							:				Union[str, Any]          =      torchvision.transforms.CenterCrop(224							)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.resize(__magic_name__							)
       UpperCamelCase__							:				Dict          =      self.center_crop(__magic_name__							)
       UpperCamelCase__							:				List[str]          =      self.normalize(__magic_name__							)
       return images




   def __call__(    self,		__magic_name__=None,		__magic_name__=None,		**__magic_name__							) ->      Union[str, Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.tokenizer(text=__magic_name__,		**__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      self.preprocess_img(__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      {key: value.to(self.device							) for (key, value) in encoding.items()}
       return encoding






class     lowercase__       (	nn.Module				):

   '''simple docstring'''


   def __init__(    self,		__magic_name__=10,		__magic_name__=0.01,		__magic_name__=None,		__magic_name__=None,		__magic_name__=None,		__magic_name__=None,		__magic_name__=None,		__magic_name__=None,		__magic_name__=False,		__magic_name__=True,		__magic_name__="image",		__magic_name__=True,		__magic_name__=False,		__magic_name__=False,		__magic_name__=False,		) ->      None:






       """simple docstring"""
       super().__init__()
       UpperCamelCase__							:				Dict          =      None
       UpperCamelCase__							:				Tuple          =      device if device else get_device()
       if vqgan:
           UpperCamelCase__							:				Union[str, Any]          =      vqgan
       else:
           UpperCamelCase__							:				Any          =      load_vqgan(self.device,		conf_path=__magic_name__,		ckpt_path=__magic_name__							)
       self.vqgan.eval()
       if clip:
           UpperCamelCase__							:				Optional[Any]          =      clip
       else:
           UpperCamelCase__							:				Any          =      CLIPModel.from_pretrained('''openai/clip-vit-base-patch32'''							)
       self.clip.to(self.device							)
       UpperCamelCase__							:				str          =      ProcessorGradientFlow(device=self.device							)

       UpperCamelCase__							:				Union[str, Any]          =      iterations
       UpperCamelCase__							:				Tuple          =      lr
       UpperCamelCase__							:				Optional[int]          =      log
       UpperCamelCase__							:				List[Any]          =      make_grid
       UpperCamelCase__							:				Optional[Any]          =      return_val
       UpperCamelCase__							:				str          =      quantize
       UpperCamelCase__							:				int          =      self.vqgan.decoder.z_shape




   def       UpperCamelCase__  (    self,		__magic_name__=None,		__magic_name__=None,		__magic_name__=5,		__magic_name__=True							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      []
       if output_path is None:
           UpperCamelCase__							:				List[str]          =      '''./animation.gif'''
       if input_path is None:
           UpperCamelCase__							:				Union[str, Any]          =      self.save_path
       UpperCamelCase__							:				Tuple          =      sorted(glob(input_path + '''/*'''							)							)
       if not len(__magic_name__							):
           raise ValueError(
               '''No images found in save path, aborting (did you pass save_intermediate=True to the generate'''
               ''' function?)'''							)
       if len(__magic_name__							) == 1:
           print('''Only one image found in save path, (did you pass save_intermediate=True to the generate function?)'''							)
       UpperCamelCase__							:				Dict          =      total_duration / len(__magic_name__							)
       UpperCamelCase__							:				List[Any]          =      [frame_duration] * len(__magic_name__							)
       if extend_frames:
           UpperCamelCase__							:				List[Any]          =      1.5
           UpperCamelCase__							:				Any          =      3
       for file_name in paths:
           if file_name.endswith('''.png'''							):
               images.append(imageio.imread(__magic_name__							)							)
       imageio.mimsave(__magic_name__,		__magic_name__,		duration=__magic_name__							)
       print(f"gif saved to {output_path}"							)




   def       UpperCamelCase__  (    self,		__magic_name__=None,		__magic_name__=None							) ->      Any:






       """simple docstring"""
       if not (path or img):
           raise ValueError('''Input either path or tensor'''							)
       if img is not None:
           raise NotImplementedError
       UpperCamelCase__							:				List[Any]          =      preprocess(Image.open(__magic_name__							),		target_image_size=256							).to(self.device							)
       UpperCamelCase__							:				str          =      preprocess_vqgan(__magic_name__							)
       UpperCamelCase__   ,*UpperCamelCase__							:				Union[str, Any]          =      self.vqgan.encode(__magic_name__							)
       return z




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				Optional[Any]          =      self.latent.detach().requires_grad_()
       UpperCamelCase__							:				Any          =      base_latent + transform_vector
       if self.quantize:
           UpperCamelCase__   ,*UpperCamelCase__							:				int          =      self.vqgan.quantize(__magic_name__							)
       else:
           UpperCamelCase__							:				Optional[int]          =      trans_latent
       return self.vqgan.decode(__magic_name__							)




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__=None							) ->      Tuple:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      self.clip_preprocessor(text=__magic_name__,		images=__magic_name__,		return_tensors='''pt''',		padding=__magic_name__							)
       UpperCamelCase__							:				Optional[int]          =      self.clip(**__magic_name__							)
       UpperCamelCase__							:				Tuple          =      clip_outputs.logits_per_image
       if weights is not None:
           UpperCamelCase__							:				List[Any]          =      similarity_logits * weights
       return similarity_logits.sum()




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Any:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      self._get_clip_similarity(pos_prompts['''prompts'''],		__magic_name__,		weights=(1 / pos_prompts['''weights'''])							)
       if neg_prompts:
           UpperCamelCase__							:				Tuple          =      self._get_clip_similarity(neg_prompts['''prompts'''],		__magic_name__,		weights=neg_prompts['''weights''']							)
       else:
           UpperCamelCase__							:				Optional[int]          =      torch.tensor([1],		device=self.device							)
       UpperCamelCase__							:				Tuple          =      -torch.log(__magic_name__							) + torch.log(__magic_name__							)
       return loss




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__							) ->      Optional[Any]:






       """simple docstring"""
       UpperCamelCase__							:				List[str]          =      torch.randn_like(self.latent,		requires_grad=__magic_name__,		device=self.device							)
       UpperCamelCase__							:				Optional[int]          =      torch.optim.Adam([vector],		lr=self.lr							)

       for i in range(self.iterations							):
           optim.zero_grad()
           UpperCamelCase__							:				Tuple          =      self._add_vector(__magic_name__							)
           UpperCamelCase__							:				Any          =      loop_post_process(__magic_name__							)
           UpperCamelCase__							:				Union[str, Any]          =      self._get_CLIP_loss(__magic_name__,		__magic_name__,		__magic_name__							)
           print('''CLIP loss''',		__magic_name__							)
           if self.log:
               wandb.log({'''CLIP Loss''': clip_loss}							)
           clip_loss.backward(retain_graph=__magic_name__							)
           optim.step()
           if self.return_val == "image":
               yield custom_to_pil(transformed_img[0]							)
           else:
               yield vector




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__,		__magic_name__							) ->      List[str]:






       """simple docstring"""
       wandb.init(reinit=__magic_name__,		project='''face-editor'''							)
       wandb.config.update({'''Positive Prompts''': positive_prompts}							)
       wandb.config.update({'''Negative Prompts''': negative_prompts}							)
       wandb.config.update({'''lr''': self.lr, '''iterations''': self.iterations}							)
       if image_path:
           UpperCamelCase__							:				List[str]          =      Image.open(__magic_name__							)
           UpperCamelCase__							:				List[Any]          =      image.resize((256, 256)							)
           wandb.log('''Original Image''',		wandb.Image(__magic_name__							)							)




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Optional[int]:






       """simple docstring"""
       if not prompts:
           return []
       UpperCamelCase__							:				int          =      []
       UpperCamelCase__							:				str          =      []
       if isinstance(__magic_name__,		__magic_name__							):
           UpperCamelCase__							:				Optional[Any]          =      [prompt.strip() for prompt in prompts.split('''|'''							)]
       for prompt in prompts:
           if isinstance(__magic_name__,		(tuple, list)							):
               UpperCamelCase__							:				Optional[int]          =      prompt[0]
               UpperCamelCase__							:				Dict          =      float(prompt[1]							)
           elif ":" in prompt:
               UpperCamelCase__   ,UpperCamelCase__							:				Optional[int]          =      prompt.split(''':'''							)
               UpperCamelCase__							:				List[Any]          =      float(__magic_name__							)
           else:
               UpperCamelCase__							:				List[str]          =      prompt
               UpperCamelCase__							:				Any          =      1.0
           processed_prompts.append(__magic_name__							)
           weights.append(__magic_name__							)
       return {
           "prompts": processed_prompts,
           "weights": torch.tensor(__magic_name__,		device=self.device							),
       }




   def       UpperCamelCase__  (    self,		__magic_name__,		__magic_name__=None,		__magic_name__=None,		__magic_name__=True,		__magic_name__=False,		__magic_name__=True,		__magic_name__=True,		__magic_name__=None,		) ->      str:






       """simple docstring"""
       if image_path:
           UpperCamelCase__							:				Union[str, Any]          =      self._get_latent(__magic_name__							)
       else:
           UpperCamelCase__							:				Dict          =      torch.randn(self.latent_dim,		device=self.device							)
       if self.log:
           self._init_logging(__magic_name__,		__magic_name__,		__magic_name__							)

       assert pos_prompts, "You must provide at least one positive prompt."
       UpperCamelCase__							:				Optional[Any]          =      self.process_prompts(__magic_name__							)
       UpperCamelCase__							:				Union[str, Any]          =      self.process_prompts(__magic_name__							)
       if save_final and save_path is None:
           UpperCamelCase__							:				str          =      os.path.join('''./outputs/''',		'''_'''.join(pos_prompts['''prompts''']							)							)
       if not os.path.exists(__magic_name__							):
           os.makedirs(__magic_name__							)
       else:
           UpperCamelCase__							:				int          =      save_path + '''_''' + get_timestamp()
           os.makedirs(__magic_name__							)
       UpperCamelCase__							:				Optional[Any]          =      save_path

       UpperCamelCase__							:				str          =      self.vqgan.decode(self.latent							)[0]
       if show_intermediate:
           print('''Original Image'''							)
           show_pil(custom_to_pil(__magic_name__							)							)

       UpperCamelCase__							:				Optional[Any]          =      loop_post_process(__magic_name__							)
       for iter, transformed_img in enumerate(self._optimize_CLIP(__magic_name__,		__magic_name__,		__magic_name__							)							):
           if show_intermediate:
               show_pil(__magic_name__							)
           if save_intermediate:
               transformed_img.save(os.path.join(self.save_path,		f"iter_{iter:03d}.png"							)							)
           if self.log:
               wandb.log({'''Image''': wandb.Image(__magic_name__							)}							)
       if show_final:
           show_pil(__magic_name__							)
       if save_final:
           transformed_img.save(os.path.join(self.save_path,		f"iter_{iter:03d}_final.png"							)							)

