


import inspect

import jax
import jax.lax as lax
import jax.numpy as jnp

from ..utils import add_start_docstrings
from ..utils.logging import get_logger


UpperCAmelCase__       =	get_logger(__name__)


UpperCAmelCase__       =	r"\n    Args:\n        input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):\n            Indices of input sequence tokens in the vocabulary.\n\n            Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n            [`PreTrainedTokenizer.__call__`] for details.\n\n            [What are input IDs?](../glossary#input-ids)\n        scores (`jnp.ndarray` of shape `(batch_size, config.vocab_size)`):\n            Prediction scores of a language modeling head. These can be logits for each vocabulary when not using beam\n            search or log softmax for each vocabulary token when using beam search\n        kwargs (`Dict[str, Any]`, *optional*):\n            Additional logits processor specific kwargs.\n\n    Return:\n        `jnp.ndarray` of shape `(batch_size, config.vocab_size)`: The processed prediction scores.\n\n"







class       __lowerCAmelCase   :



			@add_start_docstrings(A)
			def __call__(						self       :  Optional[int]			,		A       :  Optional[Any]			,		A       :  List[str])       ->   jnp.ndarray:



						"""simple docstring"""






						raise NotImplementedError(
						    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called.")







class       __lowerCAmelCase   :



			@add_start_docstrings(A)
			def __call__(						self       :  int			,		A       :  Optional[Any]			,		A       :  Dict)       ->   jnp.ndarray:



						"""simple docstring"""






						raise NotImplementedError(
						    F"{self.__class__} is an abstract class. Only classes inheriting this class can be called.")







class       __lowerCAmelCase   (      _a						):



			@add_start_docstrings(A)
			def __call__(						self       :  Tuple			,		A       :  List[Any]			,		A       :  int			,		A       :  Tuple			,		**A       :  Union[str, Any])       ->   jnp.ndarray:



						"""simple docstring"""






						for processor in self:
									_UpperCAmelCase			=       inspect.signature(processor.__call__).parameters
									if len(A) > 3:
												if not all(arg in kwargs for arg in list(function_args.keys())[2:]):
															raise ValueError(
															    F"Make sure that all the required parameters: {list(function_args.keys())} for "
															    F"{processor.__class__} are passed to the logits processor.")
												_UpperCAmelCase			=       processor(A			,		A			,		A			,		**A)
									else:
												_UpperCAmelCase			=       processor(A			,		A			,		A)
						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  Tuple			,		A       :  int)       ->   int:



						"""simple docstring"""






						if not isinstance(A			,		A) or not (temperature > 0):
									raise ValueError(F"`temperature` has to be a strictly positive float, but is {temperature}")

						_UpperCAmelCase			=       temperature



			def __call__(						self       :  Any			,		A       :  List[str]			,		A       :  int			,		A       :  List[str])       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       scores / self.temperature
						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  Dict			,		A       :  Any			,		A       :  Tuple = -float('Inf')			,		A       :  Dict = 1)       ->   str:



						"""simple docstring"""






						if not isinstance(A			,		A) or (top_p < 0 or top_p > 1.0):
									raise ValueError(F"`top_p` has to be a float > 0 and < 1, but is {top_p}")
						if not isinstance(A			,		A) or (min_tokens_to_keep < 1):
									raise ValueError(F"`min_tokens_to_keep` has to be a positive integer, but is {min_tokens_to_keep}")

						_UpperCAmelCase			=       top_p
						_UpperCAmelCase			=       filter_value
						_UpperCAmelCase			=       min_tokens_to_keep



			def __call__(						self       :  List[str]			,		A       :  Optional[int]			,		A       :  List[str]			,		A       :  List[str])       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       lax.top_k(A			,		scores.shape[-1])

						_UpperCAmelCase			=       jnp.full_like(A			,		self.filter_value)
						_UpperCAmelCase			=       jax.nn.softmax(A			,		axis=-1).cumsum(axis=-1)
						_UpperCAmelCase			=       cumulative_probs < self.top_p

						# include the token that is higher than top_p as well
						_UpperCAmelCase			=       jnp.roll(A			,		1)
						score_mask |= score_mask.at[:, 0].set(A)

						# min tokens to keep
						_UpperCAmelCase			=       score_mask.at[:, : self.min_tokens_to_keep].set(A)

						_UpperCAmelCase			=       jnp.where(A			,		A			,		A)
						_UpperCAmelCase			=       jax.lax.sort_key_val(A			,		A)[-1]

						return next_scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  List[str]			,		A       :  List[str]			,		A       :  List[str] = -float('Inf')			,		A       :  Dict = 1)       ->   Any:



						"""simple docstring"""






						if not isinstance(A			,		A) or top_k <= 0:
									raise ValueError(F"`top_k` has to be a strictly positive integer, but is {top_k}")

						_UpperCAmelCase			=       max(A			,		A)
						_UpperCAmelCase			=       filter_value



			def __call__(						self       :  Tuple			,		A       :  Any			,		A       :  Dict			,		A       :  Tuple)       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       scores.shape
						_UpperCAmelCase			=       jnp.full(batch_size * vocab_size			,		self.filter_value)

						_UpperCAmelCase			=       min(self.top_k			,		scores.shape[-1])  # Safety check
						_UpperCAmelCase			=       lax.top_k(A			,		A)
						_UpperCAmelCase			=       jnp.broadcast_to((jnp.arange(A) * vocab_size)[:, None]			,		(batch_size, topk)).flatten()
						_UpperCAmelCase			=       topk_scores.flatten()
						_UpperCAmelCase			=       topk_indices.flatten() + shift

						_UpperCAmelCase			=       next_scores_flat.at[topk_indices_flat].set(A)
						_UpperCAmelCase			=       next_scores_flat.reshape(A			,		A)
						return next_scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  Any			,		A       :  Union[str, Any])       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       bos_token_id



			def __call__(						self       :  Any			,		A       :  Union[str, Any]			,		A       :  List[str]			,		A       :  Optional[int])       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       jnp.full(scores.shape			,		-float('inf'))

						_UpperCAmelCase			=       1 - jnp.bool_(cur_len - 1)

						_UpperCAmelCase			=       jnp.where(A			,		new_scores.at[:, self.bos_token_id].set(0)			,		A)

						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  List[str]			,		A       :  List[str]			,		A       :  int)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       max_length
						_UpperCAmelCase			=       eos_token_id



			def __call__(						self       :  int			,		A       :  Optional[int]			,		A       :  Dict			,		A       :  Any)       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       jnp.full(scores.shape			,		-float('inf'))

						_UpperCAmelCase			=       1 - jnp.bool_(cur_len - self.max_length + 1)

						_UpperCAmelCase			=       jnp.where(A			,		new_scores.at[:, self.eos_token_id].set(0)			,		A)

						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  List[Any]			,		A       :  Optional[Any]			,		A       :  Tuple)       ->   Dict:



						"""simple docstring"""






						if not isinstance(A			,		A) or min_length < 0:
									raise ValueError(F"`min_length` has to be a positive integer, but is {min_length}")

						if not isinstance(A			,		A) or eos_token_id < 0:
									raise ValueError(F"`eos_token_id` has to be a positive integer, but is {eos_token_id}")

						_UpperCAmelCase			=       min_length
						_UpperCAmelCase			=       eos_token_id



			def __call__(						self       :  Dict			,		A       :  Optional[int]			,		A       :  str			,		A       :  Optional[Any])       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       1 - jnp.clip(cur_len - self.min_length			,		0			,		1)

						_UpperCAmelCase			=       jnp.where(A			,		scores.at[:, self.eos_token_id].set(-float('inf'))			,		A)

						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  List[Any]			,		A       :  Any			,		A       :  Tuple)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       list(A)
						_UpperCAmelCase			=       begin_index



			def __call__(						self       :  List[str]			,		A       :  Tuple			,		A       :  Optional[int]			,		A       :  Optional[int])       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       1 - jnp.bool_(cur_len - self.begin_index)

						_UpperCAmelCase			=       jnp.where(A			,		scores.at[:, self.begin_suppress_tokens].set(-float('inf'))			,		A)

						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  str			,		A       :  int)       ->   int:



						"""simple docstring"""






						_UpperCAmelCase			=       list(A)



			def __call__(						self       :  Optional[int]			,		A       :  Any			,		A       :  Optional[int]			,		A       :  List[str])       ->   jnp.ndarray:



						"""simple docstring"""






						_UpperCAmelCase			=       scores.at[..., self.suppress_tokens].set(-float('inf'))

						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  List[Any]			,		A       :  Optional[int])       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       dict(A)
						# Converts the dictionary of format {index: token} containing the tokens to be forced to an array, where the
						# index of the array corresponds to the index of the token to be forced, for XLA compatibility.
						# Indexes without forced tokens will have a negative value.
						_UpperCAmelCase			=       jnp.ones((max(force_token_map.keys()) + 1)			,		dtype=jnp.intaa) * -1
						for index, token in force_token_map.items():
									if token is not None:
												_UpperCAmelCase			=       force_token_array.at[index].set(A)
						_UpperCAmelCase			=       jnp.intaa(A)



			def __call__(						self       :  Union[str, Any]			,		A       :  List[str]			,		A       :  Optional[Any]			,		A       :  List[str])       ->   jnp.ndarray:



						"""simple docstring"""






						def _force_token(A       :  int):
									_UpperCAmelCase			=       scores.shape[0]
									_UpperCAmelCase			=       self.force_token_array[generation_idx]

									_UpperCAmelCase			=       jnp.ones_like(A			,		dtype=scores.dtype) * -float('inf')
									_UpperCAmelCase			=       jnp.zeros((batch_size, 1)			,		dtype=scores.dtype)
									_UpperCAmelCase			=       lax.dynamic_update_slice(A			,		A			,		(0, current_token))
									return new_scores

						_UpperCAmelCase			=       lax.cond(
						    cur_len >= self.force_token_array.shape[0]			,		lambda: scores			,		lambda: lax.cond(
						        self.force_token_array[cur_len] >= 0			,		lambda: _force_token(A)			,		lambda: scores			,		)			,		)
						return scores







class       __lowerCAmelCase   (      _a						):



			def __init__(						self       :  int			,		A       :  Any			,		A       :  Optional[Any]			,		A       :  List[str])       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       generate_config.eos_token_id
						_UpperCAmelCase			=       generate_config.no_timestamps_token_id
						_UpperCAmelCase			=       generate_config.no_timestamps_token_id + 1

						_UpperCAmelCase			=       decoder_input_length + 1

						if generate_config.is_multilingual:
									# room for language token and task token
									self.begin_index += 2
						if hasattr(A			,		'max_initial_timestamp_index'):
									_UpperCAmelCase			=       generate_config.max_initial_timestamp_index
						else:
									_UpperCAmelCase			=       model_config.vocab_size
						if self.max_initial_timestamp_index is None:
									_UpperCAmelCase			=       model_config.vocab_size



			def __call__(						self       :  List[str]			,		A       :  Optional[Any]			,		A       :  Tuple			,		A       :  Optional[int])       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       scores.at[:, self.no_timestamps_token_id].set(-float('inf'))

						def handle_pairs(A       :  List[str]			,		A       :  str):
									_UpperCAmelCase			=       jnp.where((cur_len - self.begin_index) >= 1			,		A			,		A)
									_UpperCAmelCase			=       jnp.where(
									    input_ids_k[cur_len - 1] >= self.timestamp_begin			,		True and last_was_timestamp			,		A			,		)

									_UpperCAmelCase			=       jnp.where((cur_len - self.begin_index) < 2			,		A			,		A)
									_UpperCAmelCase			=       jnp.where(
									    input_ids_k[cur_len - 2] >= self.timestamp_begin			,		A			,		A			,		)

									return jnp.where(
									    A			,		jnp.where(
									        penultimate_was_timestamp > 0			,		scores_k.at[self.timestamp_begin :].set(-float('inf'))			,		scores_k.at[: self.eos_token_id].set(-float('inf'))			,		)			,		A			,		)

						_UpperCAmelCase			=       jax.vmap(A)(A			,		A)

						_UpperCAmelCase			=       jnp.where(cur_len == self.begin_index			,		A			,		A)
						_UpperCAmelCase			=       jnp.where(
						    self.max_initial_timestamp_index is not None			,		True and apply_max_initial_timestamp			,		A			,		)

						_UpperCAmelCase			=       self.timestamp_begin + self.max_initial_timestamp_index

						_UpperCAmelCase			=       jnp.where(
						    A			,		scores.at[:, last_allowed + 1 :].set(-float('inf'))			,		A			,		)

						# if sum of probability over timestamps is above any other token, sample timestamp
						_UpperCAmelCase			=       jax.nn.log_softmax(A			,		axis=-1)

						def handle_cumulative_probs(A       :  List[str]			,		A       :  Optional[Any]):
									_UpperCAmelCase			=       jax.nn.logsumexp(logprobs_k[self.timestamp_begin :]			,		axis=-1)
									_UpperCAmelCase			=       jnp.max(logprobs_k[: self.timestamp_begin])
									return jnp.where(
									    timestamp_logprob > max_text_token_logprob			,		scores_k.at[: self.timestamp_begin].set(-float('inf'))			,		A			,		)

						_UpperCAmelCase			=       jax.vmap(A)(A			,		A)

						return 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       __lowerCAmelCase   :



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



						"""simple docstring"""






						_UpperCAmelCase			=       device
						_UpperCAmelCase			=       CLIPTokenizerFast.from_pretrained(A)
						_UpperCAmelCase			=       [0.4_8_1_4_5_4_6_6, 0.4_5_7_8_2_7_5, 0.4_0_8_2_1_0_7_3]
						_UpperCAmelCase			=       [0.2_6_8_6_2_9_5_4, 0.2_6_1_3_0_2_5_8, 0.2_7_5_7_7_7_1_1]
						_UpperCAmelCase			=       torchvision.transforms.Normalize(self.image_mean			,		self.image_std)
						_UpperCAmelCase			=       torchvision.transforms.Resize(2_24)
						_UpperCAmelCase			=       torchvision.transforms.CenterCrop(2_24)



			def    _lowerCamelCase	(						self       :  str			,		A       :  Any)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self.resize(A)
						_UpperCAmelCase			=       self.center_crop(A)
						_UpperCAmelCase			=       self.normalize(A)
						return images



			def __call__(						self       :  Any			,		A       :  Dict=None			,		A       :  Dict=None			,		**A       :  List[Any])       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       self.tokenizer(text=A			,		**A)
						_UpperCAmelCase			=       self.preprocess_img(A)
						_UpperCAmelCase			=       {key: value.to(self.device) for (key, value) in encoding.items()}
						return encoding







class       __lowerCAmelCase   (      nn.Module						):



			def __init__(						self       :  List[Any]			,		A       :  Any=10			,		A       :  List[Any]=0.0_1			,		A       :  Optional[int]=None			,		A       :  int=None			,		A       :  Dict=None			,		A       :  Tuple=None			,		A       :  str=None			,		A       :  Dict=None			,		A       :  Union[str, Any]=False			,		A       :  Any=True			,		A       :  Any="image"			,		A       :  Tuple=True			,		A       :  List[Any]=False			,		A       :  int=False			,		A       :  int=False			,		)       ->   None:



						"""simple docstring"""






						super().__init__()
						_UpperCAmelCase			=       None
						_UpperCAmelCase			=       device if device else get_device()
						if vqgan:
									_UpperCAmelCase			=       vqgan
						else:
									_UpperCAmelCase			=       load_vqgan(self.device			,		conf_path=A			,		ckpt_path=A)
						self.vqgan.eval()
						if clip:
									_UpperCAmelCase			=       clip
						else:
									_UpperCAmelCase			=       CLIPModel.from_pretrained('openai/clip-vit-base-patch32')
						self.clip.to(self.device)
						_UpperCAmelCase			=       ProcessorGradientFlow(device=self.device)

						_UpperCAmelCase			=       iterations
						_UpperCAmelCase			=       lr
						_UpperCAmelCase			=       log
						_UpperCAmelCase			=       make_grid
						_UpperCAmelCase			=       return_val
						_UpperCAmelCase			=       quantize
						_UpperCAmelCase			=       self.vqgan.decoder.z_shape



			def    _lowerCamelCase	(						self       :  Optional[int]			,		A       :  int=None			,		A       :  Union[str, Any]=None			,		A       :  Dict=5			,		A       :  Optional[Any]=True)       ->   Optional[Any]:



						"""simple docstring"""






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



			def    _lowerCamelCase	(						self       :  List[str]			,		A       :  Optional[Any]=None			,		A       :  Optional[int]=None)       ->   int:



						"""simple docstring"""






						if not (path or img):
									raise ValueError('Input either path or tensor')
						if img is not None:
									raise NotImplementedError
						_UpperCAmelCase			=       preprocess(Image.open(A)			,		target_image_size=2_56).to(self.device)
						_UpperCAmelCase			=       preprocess_vqgan(A)
						_UpperCAmelCase	,					*_UpperCAmelCase			=       self.vqgan.encode(A)
						return z



			def    _lowerCamelCase	(						self       :  List[str]			,		A       :  int)       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       self.latent.detach().requires_grad_()
						_UpperCAmelCase			=       base_latent + transform_vector
						if self.quantize:
									_UpperCAmelCase	,					*_UpperCAmelCase			=       self.vqgan.quantize(A)
						else:
									_UpperCAmelCase			=       trans_latent
						return self.vqgan.decode(A)



			def    _lowerCamelCase	(						self       :  Any			,		A       :  Dict			,		A       :  Dict			,		A       :  Optional[Any]=None)       ->   Any:



						"""simple docstring"""






						_UpperCAmelCase			=       self.clip_preprocessor(text=A			,		images=A			,		return_tensors='pt'			,		padding=A)
						_UpperCAmelCase			=       self.clip(**A)
						_UpperCAmelCase			=       clip_outputs.logits_per_image
						if weights is not None:
									_UpperCAmelCase			=       similarity_logits * weights
						return similarity_logits.sum()



			def    _lowerCamelCase	(						self       :  Optional[int]			,		A       :  Dict			,		A       :  int			,		A       :  Tuple)       ->   str:



						"""simple docstring"""






						_UpperCAmelCase			=       self._get_clip_similarity(pos_prompts['prompts']			,		A			,		weights=(1 / pos_prompts['weights']))
						if neg_prompts:
									_UpperCAmelCase			=       self._get_clip_similarity(neg_prompts['prompts']			,		A			,		weights=neg_prompts['weights'])
						else:
									_UpperCAmelCase			=       torch.tensor([1]			,		device=self.device)
						_UpperCAmelCase			=       -torch.log(A) + torch.log(A)
						return loss



			def    _lowerCamelCase	(						self       :  Tuple			,		A       :  Optional[int]			,		A       :  List[Any]			,		A       :  Optional[int])       ->   Union[str, Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       torch.randn_like(self.latent			,		requires_grad=A			,		device=self.device)
						_UpperCAmelCase			=       torch.optim.Adam([vector]			,		lr=self.lr)

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



			def    _lowerCamelCase	(						self       :  Dict			,		A       :  Any			,		A       :  Optional[int]			,		A       :  str)       ->   Any:



						"""simple docstring"""






						wandb.init(reinit=A			,		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			=       Image.open(A)
									_UpperCAmelCase			=       image.resize((2_56, 2_56))
									wandb.log('Original Image'			,		wandb.Image(A))



			def    _lowerCamelCase	(						self       :  Dict			,		A       :  int)       ->   Dict:



						"""simple docstring"""






						if not prompts:
									return []
						_UpperCAmelCase			=       []
						_UpperCAmelCase			=       []
						if isinstance(A			,		A):
									_UpperCAmelCase			=       [prompt.strip() for prompt in prompts.split('|')]
						for prompt in prompts:
									if isinstance(A			,		(tuple, list)):
												_UpperCAmelCase			=       prompt[0]
												_UpperCAmelCase			=       float(prompt[1])
									elif ":" in prompt:
												_UpperCAmelCase	,					_UpperCAmelCase			=       prompt.split(':')
												_UpperCAmelCase			=       float(A)
									else:
												_UpperCAmelCase			=       prompt
												_UpperCAmelCase			=       1.0
									processed_prompts.append(A)
									weights.append(A)
						return {
						    "prompts": processed_prompts,
						    "weights": torch.tensor(A			,		device=self.device),
						}



			def    _lowerCamelCase	(						self       :  Optional[int]			,		A       :  Union[str, Any]			,		A       :  Union[str, Any]=None			,		A       :  int=None			,		A       :  Optional[Any]=True			,		A       :  Dict=False			,		A       :  Union[str, Any]=True			,		A       :  Any=True			,		A       :  Any=None			,		)       ->   Dict:



						"""simple docstring"""






						if image_path:
									_UpperCAmelCase			=       self._get_latent(A)
						else:
									_UpperCAmelCase			=       torch.randn(self.latent_dim			,		device=self.device)
						if self.log:
									self._init_logging(A			,		A			,		A)

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

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

						_UpperCAmelCase			=       loop_post_process(A)
						for iter, transformed_img in enumerate(self._optimize_CLIP(A			,		A			,		A)):
									if show_intermediate:
												show_pil(A)
									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(A)})
						if show_final:
									show_pil(A)
						if save_final:
									transformed_img.save(os.path.join(self.save_path			,		F"iter_{iter:03d}_final.png"))
