






'''simple docstring'''

from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


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

UpperCamelCase      					="\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e-img2img\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = \"https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png\"\n        >>> image = load_image(image_url).convert(\"RGB\")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], \"corgi_3d.gif\")\n        ```\n"




@dataclass
class      A     (   SCREAMING_SNAKE_CASE__    ):






 """simple docstring"""





 __a      :    Union[PIL.Image.Image, np.ndarray]






class      A     (   SCREAMING_SNAKE_CASE__    ):






 """simple docstring"""





 def __init__(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  ):
       super().__init__()

       self.register_modules(
           prior=__lowerCAmelCase      ,  image_encoder=__lowerCAmelCase      ,  image_processor=__lowerCAmelCase      ,  scheduler=__lowerCAmelCase      ,  renderer=__lowerCAmelCase      ,  )
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			):
       if latents is None:
             UpperCamelCase_					: Any            =				randn_tensor(__lowerCAmelCase      ,  generator=__lowerCAmelCase      ,  device=__lowerCAmelCase      ,  dtype=__lowerCAmelCase			)
       else:
             if latents.shape != shape:
                   raise ValueError(F"Unexpected latents shape, got {latents.shape}, expected {shape}"			)
             UpperCamelCase_					: Dict            =				latents.to(__lowerCAmelCase			)

       UpperCamelCase_					: Optional[int]            =				latents * scheduler.init_noise_sigma
       return latents
 def 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase=0			):
       if is_accelerate_available():
             from accelerate import cpu_offload
       else:
             raise ImportError("""Please install accelerate via `pip install accelerate`"""			)

       UpperCamelCase_					: Any            =				torch.device(F"cuda:{gpu_id}"			)

       UpperCamelCase_					: Dict            =				[self.image_encoder, self.prior]
       for cpu_offloaded_model in models:
             if cpu_offloaded_model is not None:
                   cpu_offload(__lowerCAmelCase      ,  __lowerCAmelCase			)
 @property
 def 	_UpperCAmelCase							(				self			):
       if self.device != torch.device("""meta"""			) or not hasattr(self.image_encoder      ,  """_hf_hook"""			):
             return self.device
       for module in self.image_encoder.modules():
             if (
                 hasattr(__lowerCAmelCase      ,  """_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 	_UpperCAmelCase							(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  ):
       if isinstance(__lowerCAmelCase      ,  __lowerCAmelCase			) and isinstance(image[0]      ,  torch.Tensor			):
             UpperCamelCase_					: Any            =				torch.cat(__lowerCAmelCase      ,  axis=0			) if image[0].ndim == 4 else torch.stack(__lowerCAmelCase      ,  axis=0			)

       if not isinstance(__lowerCAmelCase      ,  torch.Tensor			):
             UpperCamelCase_					: Optional[Any]            =				self.image_processor(__lowerCAmelCase      ,  return_tensors="""pt"""			).pixel_values[0].unsqueeze(0			)

       UpperCamelCase_					: List[str]            =				image.to(dtype=self.image_encoder.dtype      ,  device=__lowerCAmelCase			)

       UpperCamelCase_					: str            =				self.image_encoder(__lowerCAmelCase			)["""last_hidden_state"""]
       UpperCamelCase_					: int            =				image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

       UpperCamelCase_					: Union[str, Any]            =				image_embeds.repeat_interleave(__lowerCAmelCase      ,  dim=0			)

       if do_classifier_free_guidance:
             UpperCamelCase_					: Any            =				torch.zeros_like(__lowerCAmelCase			)

             # 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
             UpperCamelCase_					: int            =				torch.cat([negative_image_embeds, image_embeds]			)

       return image_embeds





 @torch.no_grad()
 @replace_example_docstring(__lowerCAmelCase			)
 def __call__(				self      ,  __lowerCAmelCase      ,  __lowerCAmelCase = 1      ,  __lowerCAmelCase = 25      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = None      ,  __lowerCAmelCase = 4.0      ,  __lowerCAmelCase = 64      ,  __lowerCAmelCase = "pil"      ,  __lowerCAmelCase = True      ,  ):

       if isinstance(__lowerCAmelCase      ,  PIL.Image.Image			):
             UpperCamelCase_					: Union[str, Any]            =				1
       elif isinstance(__lowerCAmelCase      ,  torch.Tensor			):
             UpperCamelCase_					: List[str]            =				image.shape[0]
       elif isinstance(__lowerCAmelCase      ,  __lowerCAmelCase			) and isinstance(image[0]      ,  (torch.Tensor, PIL.Image.Image)			):
             UpperCamelCase_					: List[Any]            =				len(__lowerCAmelCase			)
       else:
             raise ValueError(
                 F"`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(__lowerCAmelCase			)}"			)

       UpperCamelCase_					: Union[str, Any]            =				self._execution_device

       UpperCamelCase_					: List[Any]            =				batch_size * num_images_per_prompt

       UpperCamelCase_					: Optional[Any]            =				guidance_scale > 1.0
       UpperCamelCase_					: str            =				self._encode_image(__lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)

       # prior

       self.scheduler.set_timesteps(__lowerCAmelCase      ,  device=__lowerCAmelCase			)
       UpperCamelCase_					: str            =				self.scheduler.timesteps

       UpperCamelCase_					: List[str]            =				self.prior.config.num_embeddings
       UpperCamelCase_					: str            =				self.prior.config.embedding_dim

       UpperCamelCase_					: Union[str, Any]            =				self.prepare_latents(
           (batch_size, num_embeddings * embedding_dim)      ,  image_embeds.dtype      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  __lowerCAmelCase      ,  self.scheduler      ,  )

       # YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
       UpperCamelCase_					: Dict            =				latents.reshape(latents.shape[0]      ,  __lowerCAmelCase      ,  __lowerCAmelCase			)

       for i, t in enumerate(self.progress_bar(__lowerCAmelCase			)			):
             # expand the latents if we are doing classifier free guidance
             UpperCamelCase_					: int            =				torch.cat([latents] * 2			) if do_classifier_free_guidance else latents
             UpperCamelCase_					: Tuple            =				self.scheduler.scale_model_input(__lowerCAmelCase      ,  __lowerCAmelCase			)

             UpperCamelCase_					: Dict            =				self.prior(
                 __lowerCAmelCase      ,  timestep=__lowerCAmelCase      ,  proj_embedding=__lowerCAmelCase      ,  ).predicted_image_embedding

             # remove the variance
             UpperCamelCase_     ,      UpperCamelCase_					: Optional[Any]            =				noise_pred.split(
                 scaled_model_input.shape[2]      ,  dim=2			)  # batch_size, num_embeddings, embedding_dim

             if do_classifier_free_guidance is not None:
                   UpperCamelCase_     ,      UpperCamelCase_					: Tuple            =				noise_pred.chunk(2			)
                   UpperCamelCase_					: List[str]            =				noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

             UpperCamelCase_					: str            =				self.scheduler.step(
                 __lowerCAmelCase      ,  timestep=__lowerCAmelCase      ,  sample=__lowerCAmelCase      ,  ).prev_sample

       if output_type == "latent":
             return ShapEPipelineOutput(images=__lowerCAmelCase			)

       UpperCamelCase_					: Optional[Any]            =				[]
       for i, latent in enumerate(__lowerCAmelCase			):
             print()
             UpperCamelCase_					: Tuple            =				self.renderer.decode(
                 latent[None, :]      ,  __lowerCAmelCase      ,  size=__lowerCAmelCase      ,  ray_batch_size=40_96      ,  n_coarse_samples=64      ,  n_fine_samples=1_28      ,  )

             images.append(__lowerCAmelCase			)

       UpperCamelCase_					: Dict            =				torch.stack(__lowerCAmelCase			)

       if output_type not in ["np", "pil"]:
             raise ValueError(F"Only the output types `pil` and `np` are supported not output_type={output_type}"			)

       UpperCamelCase_					: Any            =				images.cpu().numpy()

       if output_type == "pil":
             UpperCamelCase_					: Union[str, Any]            =				[self.numpy_to_pil(__lowerCAmelCase			) for image in images]

       # Offload last model to CPU
       if hasattr(self      ,  """final_offload_hook"""			) and self.final_offload_hook is not None:
             self.final_offload_hook.offload()

       if not return_dict:
             return (images,)

       return ShapEPipelineOutput(images=__lowerCAmelCase			)














'''simple docstring'''

def 				snake_case       (  a_				:			int						)							->					int:





      """simple docstring"""

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

            return sequence[n]



def 				snake_case       (  a_				:			int						)							->					int:





      """simple docstring"""

      UpperCamelCase_					: Any            =				0
      UpperCamelCase_					: Union[str, Any]            =				2

      while digits < n:
            index += 1
            UpperCamelCase_					: Any            =				len(str(fibonacci(a_						)						)						)

      return index



def 				snake_case       (  a_				:			int = 1_000						)							->					int:





      """simple docstring"""

      return fibonacci_digits_index(a_						)


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






