




'''simple docstring'''


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







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


														"""simple docstring"""


														_a			  =       device
														_a			  =       CLIPTokenizerFast.from_pretrained(lowerCAmelCase_      )
														_a			  =       [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]
														_a			  =       [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]
														_a			  =       torchvision.transforms.Normalize(self.image_mean							,    self.image_std      )
														_a			  =       torchvision.transforms.Resize(2_24      )
														_a			  =       torchvision.transforms.CenterCrop(2_24      )







							def      __lowerCAmelCase    (						self :						str							,    lowerCAmelCase_ :						Optional[int]      )    ->							Union[str, Any]:


														"""simple docstring"""


														_a			  =       self.resize(lowerCAmelCase_      )
														_a			  =       self.center_crop(lowerCAmelCase_      )
														_a			  =       self.normalize(lowerCAmelCase_      )
														return images







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


														"""simple docstring"""


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



class     A					(	nn.Module					):







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


														"""simple docstring"""


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

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







							def      __lowerCAmelCase    (						self :						Optional[Any]							,    lowerCAmelCase_ :						Optional[Any]=None							,    lowerCAmelCase_ :						Optional[Any]=None							,    lowerCAmelCase_ :						Optional[int]=5							,    lowerCAmelCase_ :						List[Any]=True      )    ->							int:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						Union[str, Any]=None							,    lowerCAmelCase_ :						Optional[Any]=None      )    ->							str:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Optional[int]							,    lowerCAmelCase_ :						Tuple      )    ->							Dict:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						List[Any]							,    lowerCAmelCase_ :						Optional[Any]							,    lowerCAmelCase_ :						Tuple							,    lowerCAmelCase_ :						List[str]=None      )    ->							List[str]:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Union[str, Any]							,    lowerCAmelCase_ :						Dict							,    lowerCAmelCase_ :						Union[str, Any]							,    lowerCAmelCase_ :						List[Any]      )    ->							List[Any]:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Any							,    lowerCAmelCase_ :						Union[str, Any]							,    lowerCAmelCase_ :						Optional[Any]							,    lowerCAmelCase_ :						Tuple      )    ->							int:


														"""simple docstring"""


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

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







							def      __lowerCAmelCase    (						self :						int							,    lowerCAmelCase_ :						str							,    lowerCAmelCase_ :						List[Any]							,    lowerCAmelCase_ :						Union[str, Any]      )    ->							Dict:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						Optional[Any]							,    lowerCAmelCase_ :						Optional[Any]      )    ->							Tuple:


														"""simple docstring"""


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







							def      __lowerCAmelCase    (						self :						List[str]							,    lowerCAmelCase_ :						Optional[int]							,    lowerCAmelCase_ :						Any=None							,    lowerCAmelCase_ :						Optional[int]=None							,    lowerCAmelCase_ :						int=True							,    lowerCAmelCase_ :						Union[str, Any]=False							,    lowerCAmelCase_ :						Any=True							,    lowerCAmelCase_ :						Union[str, Any]=True							,    lowerCAmelCase_ :						Optional[int]=None							,    )    ->							Tuple:


														"""simple docstring"""


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

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

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

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







'''simple docstring'''


def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							if n == 1 or not isinstance(UpperCamelCase				,		UpperCamelCase   ):
														return 0
							elif n == 2:
														return 1
							else:
														_a			  =       [0, 1]
														for i in range(2				,		n + 1   ):
																					sequence.append(sequence[i - 1] + sequence[i - 2]   )

														return sequence[n]
def 	snake_case_					(UpperCamelCase :						int   ):





							'''simple docstring'''


							_a			  =       0
							_a			  =       2

							while digits < n:
														index += 1
														_a			  =       len(str(fibonacci(UpperCamelCase   )   )   )

							return index
def 	snake_case_					(UpperCamelCase :						int = 1000   ):





							'''simple docstring'''


							return fibonacci_digits_index(UpperCamelCase   )


if __name__ == "__main__":
				print(solution(int(str(input()).strip())))

