



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 			_snake_case     :




				def __init__(  self   :  List[str],   __lowercase   :  str = "cpu",   __lowercase   :  str = "openai/clip-vit-large-patch14"  ):
							lowercase__   					=			device
							lowercase__   					=			CLIPTokenizerFast.from_pretrained(__lowercase  )
							lowercase__   					=			[0.48145466, 0.4578275, 0.40821073]
							lowercase__   					=			[0.26862954, 0.26130258, 0.27577711]
							lowercase__   					=			torchvision.transforms.Normalize(self.image_mean,   self.image_std  )
							lowercase__   					=			torchvision.transforms.Resize(224  )
							lowercase__   					=			torchvision.transforms.CenterCrop(224  )




				def 							A__ (  self   :  Tuple,   __lowercase   :  Tuple  ):
							lowercase__   					=			self.resize(__lowercase  )
							lowercase__   					=			self.center_crop(__lowercase  )
							lowercase__   					=			self.normalize(__lowercase  )
							return images




				def __call__(  self   :  List[Any],   __lowercase   :  Tuple=None,   __lowercase   :  Optional[Any]=None,   **__lowercase   :  List[str]  ):
							lowercase__   					=			self.tokenizer(text=__lowercase,   **__lowercase  )
							lowercase__   					=			self.preprocess_img(__lowercase  )
							lowercase__   					=			{key: value.to(self.device  ) for (key, value) in encoding.items()}
							return encoding
class 			_snake_case     (   nn.Module):




				def __init__(  self   :  Optional[int],   __lowercase   :  str=10,   __lowercase   :  Optional[int]=0.01,   __lowercase   :  int=None,   __lowercase   :  int=None,   __lowercase   :  Optional[Any]=None,   __lowercase   :  List[str]=None,   __lowercase   :  int=None,   __lowercase   :  Optional[Any]=None,   __lowercase   :  List[str]=False,   __lowercase   :  str=True,   __lowercase   :  Union[str, Any]="image",   __lowercase   :  int=True,   __lowercase   :  str=False,   __lowercase   :  Union[str, Any]=False,   __lowercase   :  Dict=False,   ):
							super().__init__()
							lowercase__   					=			None
							lowercase__   					=			device if device else get_device()
							if vqgan:
										lowercase__   					=			vqgan
							else:
										lowercase__   					=			load_vqgan(self.device,   conf_path=__lowercase,   ckpt_path=__lowercase  )
							self.vqgan.eval()
							if clip:
										lowercase__   					=			clip
							else:
										lowercase__   					=			CLIPModel.from_pretrained("openai/clip-vit-base-patch32"  )
							self.clip.to(self.device  )
							lowercase__   					=			ProcessorGradientFlow(device=self.device  )

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




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




				def 							A__ (  self   :  Dict,   __lowercase   :  List[str]=None,   __lowercase   :  int=None  ):
							if not (path or img):
										raise ValueError("Input either path or tensor"  )
							if img is not None:
										raise NotImplementedError
							lowercase__   					=			preprocess(Image.open(__lowercase  ),   target_image_size=256  ).to(self.device  )
							lowercase__   					=			preprocess_vqgan(__lowercase  )
							lowercase__					,    *lowercase__   					=			self.vqgan.encode(__lowercase  )
							return z




				def 							A__ (  self   :  List[Any],   __lowercase   :  Any  ):
							lowercase__   					=			self.latent.detach().requires_grad_()
							lowercase__   					=			base_latent + transform_vector
							if self.quantize:
										lowercase__					,    *lowercase__   					=			self.vqgan.quantize(__lowercase  )
							else:
										lowercase__   					=			trans_latent
							return self.vqgan.decode(__lowercase  )




				def 							A__ (  self   :  Any,   __lowercase   :  List[str],   __lowercase   :  Union[str, Any],   __lowercase   :  Any=None  ):
							lowercase__   					=			self.clip_preprocessor(text=__lowercase,   images=__lowercase,   return_tensors="pt",   padding=__lowercase  )
							lowercase__   					=			self.clip(**__lowercase  )
							lowercase__   					=			clip_outputs.logits_per_image
							if weights is not None:
										lowercase__   					=			similarity_logits * weights
							return similarity_logits.sum()




				def 							A__ (  self   :  Optional[Any],   __lowercase   :  int,   __lowercase   :  List[str],   __lowercase   :  int  ):
							lowercase__   					=			self._get_clip_similarity(pos_prompts["prompts"],   __lowercase,   weights=(1 / pos_prompts["weights"])  )
							if neg_prompts:
										lowercase__   					=			self._get_clip_similarity(neg_prompts["prompts"],   __lowercase,   weights=neg_prompts["weights"]  )
							else:
										lowercase__   					=			torch.tensor([1],   device=self.device  )
							lowercase__   					=			-torch.log(__lowercase  ) + torch.log(__lowercase  )
							return loss




				def 							A__ (  self   :  Dict,   __lowercase   :  Optional[int],   __lowercase   :  Any,   __lowercase   :  Union[str, Any]  ):
							lowercase__   					=			torch.randn_like(self.latent,   requires_grad=__lowercase,   device=self.device  )
							lowercase__   					=			torch.optim.Adam([vector],   lr=self.lr  )

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




				def 							A__ (  self   :  int,   __lowercase   :  Dict,   __lowercase   :  Optional[Any],   __lowercase   :  List[str]  ):
							wandb.init(reinit=__lowercase,   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:
										lowercase__   					=			Image.open(__lowercase  )
										lowercase__   					=			image.resize((256, 256)  )
										wandb.log("Original Image",   wandb.Image(__lowercase  )  )




				def 							A__ (  self   :  List[Any],   __lowercase   :  List[str]  ):
							if not prompts:
										return []
							lowercase__   					=			[]
							lowercase__   					=			[]
							if isinstance(__lowercase,   __lowercase  ):
										lowercase__   					=			[prompt.strip() for prompt in prompts.split("|"  )]
							for prompt in prompts:
										if isinstance(__lowercase,   (tuple, list)  ):
													lowercase__   					=			prompt[0]
													lowercase__   					=			float(prompt[1]  )
										elif ":" in prompt:
													lowercase__					,    lowercase__   					=			prompt.split(":"  )
													lowercase__   					=			float(__lowercase  )
										else:
													lowercase__   					=			prompt
													lowercase__   					=			1.0
										processed_prompts.append(__lowercase  )
										weights.append(__lowercase  )
							return {
							    "prompts": processed_prompts,
							    "weights": torch.tensor(__lowercase,   device=self.device  ),
							}




				def 							A__ (  self   :  Optional[Any],   __lowercase   :  Union[str, Any],   __lowercase   :  Tuple=None,   __lowercase   :  List[str]=None,   __lowercase   :  Tuple=True,   __lowercase   :  List[str]=False,   __lowercase   :  str=True,   __lowercase   :  Dict=True,   __lowercase   :  Optional[int]=None,   ):
							if image_path:
										lowercase__   					=			self._get_latent(__lowercase  )
							else:
										lowercase__   					=			torch.randn(self.latent_dim,   device=self.device  )
							if self.log:
										self._init_logging(__lowercase,   __lowercase,   __lowercase  )

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

							lowercase__   					=			self.vqgan.decode(self.latent  )[0]
							if show_intermediate:
										print("Original Image"  )
										show_pil(custom_to_pil(__lowercase  )  )

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









from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxSeqaSeqConfigWithPast
from ...utils import logging


if TYPE_CHECKING:
							from ...feature_extraction_utils import FeatureExtractionMixin
							from ...tokenization_utils_base import PreTrainedTokenizerBase
							from ...utils import TensorType

lowercase_						=       logging.get_logger(__name__)

lowercase_						=       {
    """openai/whisper-base""": """https://huggingface.co/openai/whisper-base/resolve/main/config.json""",
}

# fmt: off
lowercase_						=       [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 357, 366, 438, 532, 685,
    705, 796, 930, 1058, 1220, 1267, 1279, 1303, 1343, 1377,
    1391, 1635, 1782, 1875, 2162, 2361, 2488, 3467, 4008, 4211,
    4600, 4808, 5299, 5855, 6329, 7203, 9609, 9959, 1_0563, 1_0786,
    1_1420, 1_1709, 1_1907, 1_3163, 1_3697, 1_3700, 1_4808, 1_5306, 1_6410, 1_6791,
    1_7992, 1_9203, 1_9510, 2_0724, 2_2305, 2_2935, 2_7007, 3_0109, 3_0420, 3_3409,
    3_4949, 4_0283, 4_0493, 4_0549, 4_7282, 4_9146, 5_0257, 5_0359, 5_0360, 5_0361
]
lowercase_						=       [
    1, 2, 7, 8, 9, 10, 14, 25,
    26, 27, 28, 29, 31, 58, 59, 60, 61, 62,
    63, 90, 91, 92, 93, 359, 503, 522, 542, 873,
    893, 902, 918, 922, 931, 1350, 1853, 1982, 2460, 2627,
    3246, 3253, 3268, 3536, 3846, 3961, 4183, 4667, 6585, 6647,
    7273, 9061, 9383, 1_0428, 1_0929, 1_1938, 1_2033, 1_2331, 1_2562, 1_3793,
    1_4157, 1_4635, 1_5265, 1_5618, 1_6553, 1_6604, 1_8362, 1_8956, 2_0075, 2_1675,
    2_2520, 2_6130, 2_6161, 2_6435, 2_8279, 2_9464, 3_1650, 3_2302, 3_2470, 3_6865,
    4_2863, 4_7425, 4_9870, 5_0254, 5_0258, 5_0360, 5_0361, 5_0362
]
class 			_snake_case     (   lowercase__):
				UpperCamelCase__			:   Optional[int]       						="""whisper"""
				UpperCamelCase__			:   Optional[int]       						=["""past_key_values"""]
				UpperCamelCase__			:   Optional[Any]       						={"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""}




				def __init__(  self   :  List[Any],   __lowercase   :  List[str]=5_1865,   __lowercase   :  Dict=80,   __lowercase   :  List[Any]=6,   __lowercase   :  Union[str, Any]=4,   __lowercase   :  Tuple=6,   __lowercase   :  Dict=4,   __lowercase   :  List[Any]=1536,   __lowercase   :  Tuple=1536,   __lowercase   :  Any=0.0,   __lowercase   :  List[str]=0.0,   __lowercase   :  List[Any]=5_0257,   __lowercase   :  List[str]=True,   __lowercase   :  str=True,   __lowercase   :  int="gelu",   __lowercase   :  Tuple=256,   __lowercase   :  Tuple=0.0,   __lowercase   :  List[Any]=0.0,   __lowercase   :  Optional[int]=0.0,   __lowercase   :  List[Any]=0.02,   __lowercase   :  Union[str, Any]=False,   __lowercase   :  str=1500,   __lowercase   :  Optional[int]=448,   __lowercase   :  Optional[Any]=5_0256,   __lowercase   :  Tuple=5_0256,   __lowercase   :  Any=5_0256,   __lowercase   :  Union[str, Any]=None,   __lowercase   :  Any=[220, 5_0256],   __lowercase   :  List[Any]=False,   __lowercase   :  int=256,   __lowercase   :  int=False,   __lowercase   :  Tuple=0.05,   __lowercase   :  int=10,   __lowercase   :  Dict=2,   __lowercase   :  List[Any]=0.0,   __lowercase   :  Optional[int]=10,   __lowercase   :  Union[str, Any]=0,   __lowercase   :  Tuple=7,   **__lowercase   :  Union[str, Any],   ):
							lowercase__   					=			vocab_size
							lowercase__   					=			num_mel_bins
							lowercase__   					=			d_model
							lowercase__   					=			encoder_layers
							lowercase__   					=			encoder_attention_heads
							lowercase__   					=			decoder_layers
							lowercase__   					=			decoder_attention_heads
							lowercase__   					=			decoder_ffn_dim
							lowercase__   					=			encoder_ffn_dim
							lowercase__   					=			dropout
							lowercase__   					=			attention_dropout
							lowercase__   					=			activation_dropout
							lowercase__   					=			activation_function
							lowercase__   					=			init_std
							lowercase__   					=			encoder_layerdrop
							lowercase__   					=			decoder_layerdrop
							lowercase__   					=			use_cache
							lowercase__   					=			encoder_layers
							lowercase__   					=			scale_embedding  # scale factor will be sqrt(d_model) if True
							lowercase__   					=			max_source_positions
							lowercase__   					=			max_target_positions

							# Audio Classification-specific parameters. Feel free to ignore for other classes.
							lowercase__   					=			classifier_proj_size
							lowercase__   					=			use_weighted_layer_sum

							# fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
							lowercase__   					=			apply_spec_augment
							lowercase__   					=			mask_time_prob
							lowercase__   					=			mask_time_length
							lowercase__   					=			mask_time_min_masks
							lowercase__   					=			mask_feature_prob
							lowercase__   					=			mask_feature_length
							lowercase__   					=			mask_feature_min_masks

							lowercase__   					=			median_filter_width

							super().__init__(
							    pad_token_id=__lowercase,   bos_token_id=__lowercase,   eos_token_id=__lowercase,   is_encoder_decoder=__lowercase,   decoder_start_token_id=__lowercase,   suppress_tokens=__lowercase,   begin_suppress_tokens=__lowercase,   **__lowercase,   )
class 			_snake_case     (   lowercase__):




				@property
				def 							A__ (  self   :  str  ):
							lowercase__   					=			OrderedDict(
							    [
							        ("input_features", {0: "batch", 1: "feature_size", 2: "encoder_sequence"}),
							    ]  )
							if self.use_past:
										lowercase__   					=			{0: "batch"}
							else:
										lowercase__   					=			{0: "batch", 1: "decoder_sequence"}

							if self.use_past:
										self.fill_with_past_key_values_(__lowercase,   direction="inputs"  )

							return common_inputs




				def 							A__ (  self   :  int,   __lowercase   :  Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"],   __lowercase   :  int = -1,   __lowercase   :  int = -1,   __lowercase   :  bool = False,   __lowercase   :  Optional["TensorType"] = None,   __lowercase   :  int = 2_2050,   __lowercase   :  float = 5.0,   __lowercase   :  int = 220,   ):
							lowercase__   					=			OrderedDict()
							lowercase__   					=			OnnxConfig.generate_dummy_inputs(
							    self,   preprocessor=preprocessor.feature_extractor,   batch_size=__lowercase,   framework=__lowercase,   sampling_rate=__lowercase,   time_duration=__lowercase,   frequency=__lowercase,   )
							lowercase__   					=			encoder_inputs["input_features"].shape[2]
							lowercase__   					=			encoder_sequence_length // 2 if self.use_past else seq_length

							lowercase__   					=			super().generate_dummy_inputs(
							    preprocessor.tokenizer,   __lowercase,   __lowercase,   __lowercase,   __lowercase  )

							lowercase__   					=			encoder_inputs.pop("input_features"  )
							lowercase__   					=			decoder_inputs.pop("decoder_input_ids"  )

							if "past_key_values" in decoder_inputs:
										lowercase__   					=			decoder_inputs.pop("past_key_values"  )

							return dummy_inputs




				@property
				def 							A__ (  self   :  int  ):
							return 1e-3




