
'''simple docstring'''





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

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

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


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

A							     = "\n    Examples:\n        ```py\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif\n\n        >>> device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n        >>> repo = \"openai/shap-e\"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 15.0\n        >>> prompt = \"a shark\"\n\n        >>> images = pipe(\n        ...     prompt,\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], \"shark_3d.gif\")\n        ```\n"



@dataclass
class 			lowerCAmelCase__ (							UpperCamelCase							):



  '''simple docstring'''






  _UpperCamelCase							=			42



class 			lowerCAmelCase__ (							UpperCamelCase							):



  '''simple docstring'''






  def __init__(self	:			Optional[Any]						,			lowerCAmelCase_	:			PriorTransformer						,			lowerCAmelCase_	:			CLIPTextModelWithProjection						,			lowerCAmelCase_	:			CLIPTokenizer						,			lowerCAmelCase_	:			HeunDiscreteScheduler						,			lowerCAmelCase_	:			ShapERenderer						,			) ->							Optional[Any]:
        super().__init__()

        self.register_modules(
            prior=lowerCAmelCase_						,			text_encoder=lowerCAmelCase_						,			tokenizer=lowerCAmelCase_						,			scheduler=lowerCAmelCase_						,			renderer=lowerCAmelCase_						,			)

  def 		_lowerCamelCase						(self	:			Union[str, Any]						,			lowerCAmelCase_	:			Optional[int]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			List[str]						,			lowerCAmelCase_	:			Optional[int]     ) ->							Optional[int]:
        if latents is None:
              snake_case_    							=				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}'''     )
              snake_case_    							=				latents.to(lowerCAmelCase_     )

        snake_case_    							=				latents * scheduler.init_noise_sigma
        return latents

  def 		_lowerCamelCase						(self	:			str						,			lowerCAmelCase_	:			str=0     ) ->							List[str]:
        if is_accelerate_available():
              from accelerate import cpu_offload
        else:
              raise ImportError("Please install accelerate via `pip install accelerate`"     )

        snake_case_    							=				torch.device(f'''cuda:{gpu_id}'''     )

        snake_case_    							=				[self.text_encoder, self.prior]
        for cpu_offloaded_model in models:
              if cpu_offloaded_model is not None:
                    cpu_offload(lowerCAmelCase_						,			lowerCAmelCase_     )

  def 		_lowerCamelCase						(self	:			Dict						,			lowerCAmelCase_	:			Union[str, Any]=0     ) ->							str:
        if is_accelerate_available() and is_accelerate_version(">="						,			"0.17.0.dev0"     ):
              from accelerate import cpu_offload_with_hook
        else:
              raise ImportError("`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher."     )

        snake_case_    							=				torch.device(f'''cuda:{gpu_id}'''     )

        if self.device.type != "cpu":
              self.to("cpu"						,			silence_dtype_warnings=lowerCAmelCase_     )
              torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

        snake_case_    							=				None
        for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
              snake_case_							,						snake_case_    							=				cpu_offload_with_hook(lowerCAmelCase_						,			lowerCAmelCase_						,			prev_module_hook=lowerCAmelCase_     )

        if self.safety_checker is not None:
              snake_case_							,						snake_case_    							=				cpu_offload_with_hook(self.safety_checker						,			lowerCAmelCase_						,			prev_module_hook=lowerCAmelCase_     )

        # We'll offload the last model manually.
        snake_case_    							=				hook

  @property
  def 		_lowerCamelCase						(self	:			List[str]     ) ->							Union[str, Any]:
        if self.device != torch.device("meta"     ) or not hasattr(self.text_encoder						,			"_hf_hook"     ):
              return self.device
        for module in self.text_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 		_lowerCamelCase						(self	:			Dict						,			lowerCAmelCase_	:			Optional[Any]						,			lowerCAmelCase_	:			Any						,			lowerCAmelCase_	:			List[Any]						,			lowerCAmelCase_	:			Any						,			) ->							int:
        len(lowerCAmelCase_     ) if isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ) else 1

        # YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
        snake_case_    							=				0
        # get prompt text embeddings
        snake_case_    							=				self.tokenizer(
            lowerCAmelCase_						,			padding="max_length"						,			max_length=self.tokenizer.model_max_length						,			truncation=lowerCAmelCase_						,			return_tensors="pt"						,			)
        snake_case_    							=				text_inputs.input_ids
        snake_case_    							=				self.tokenizer(lowerCAmelCase_						,			padding="longest"						,			return_tensors="pt"     ).input_ids

        if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(lowerCAmelCase_						,			lowerCAmelCase_     ):
              snake_case_    							=				self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]     )
              logger.warning(
                  "The following part of your input was truncated because CLIP can only handle sequences up to"
                  f''' {self.tokenizer.model_max_length} tokens: {removed_text}'''     )

        snake_case_    							=				self.text_encoder(text_input_ids.to(lowerCAmelCase_     )     )
        snake_case_    							=				text_encoder_output.text_embeds

        snake_case_    							=				prompt_embeds.repeat_interleave(lowerCAmelCase_						,			dim=0     )
        # in Shap-E it normalize the prompt_embeds and then later rescale it
        snake_case_    							=				prompt_embeds / torch.linalg.norm(lowerCAmelCase_						,			dim=-1						,			keepdim=lowerCAmelCase_     )

        if do_classifier_free_guidance:
              snake_case_    							=				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
              snake_case_    							=				torch.cat([negative_prompt_embeds, prompt_embeds]     )

        # Rescale the features to have unit variance
        snake_case_    							=				math.sqrt(prompt_embeds.shape[1]     ) * prompt_embeds

        return prompt_embeds


  @torch.no_grad()
  @replace_example_docstring(lowerCAmelCase_     )
  def __call__(self	:			int						,			lowerCAmelCase_	:			str						,			lowerCAmelCase_	:			int = 1						,			lowerCAmelCase_	:			int = 25						,			lowerCAmelCase_	:			Optional[Union[torch.Generator, List[torch.Generator]]] = None						,			lowerCAmelCase_	:			Optional[torch.FloatTensor] = None						,			lowerCAmelCase_	:			float = 4.0						,			lowerCAmelCase_	:			int = 64						,			lowerCAmelCase_	:			Optional[str] = "pil"						,			lowerCAmelCase_	:			bool = True						,			) ->							Dict:

        if isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ):
              snake_case_    							=				1
        elif isinstance(lowerCAmelCase_						,			lowerCAmelCase_     ):
              snake_case_    							=				len(lowerCAmelCase_     )
        else:
              raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(lowerCAmelCase_     )}'''     )

        snake_case_    							=				self._execution_device

        snake_case_    							=				batch_size * num_images_per_prompt

        snake_case_    							=				guidance_scale > 1.0
        snake_case_    							=				self._encode_prompt(lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_						,			lowerCAmelCase_     )

        # prior

        self.scheduler.set_timesteps(lowerCAmelCase_						,			device=lowerCAmelCase_     )
        snake_case_    							=				self.scheduler.timesteps

        snake_case_    							=				self.prior.config.num_embeddings
        snake_case_    							=				self.prior.config.embedding_dim

        snake_case_    							=				self.prepare_latents(
            (batch_size, num_embeddings * embedding_dim)						,			prompt_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
        snake_case_    							=				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
              snake_case_    							=				torch.cat([latents] * 2     ) if do_classifier_free_guidance else latents
              snake_case_    							=				self.scheduler.scale_model_input(lowerCAmelCase_						,			lowerCAmelCase_     )

              snake_case_    							=				self.prior(
                  lowerCAmelCase_						,			timestep=lowerCAmelCase_						,			proj_embedding=lowerCAmelCase_						,			).predicted_image_embedding

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

              if do_classifier_free_guidance is not None:
                    snake_case_							,						snake_case_    							=				noise_pred.chunk(2     )
                    snake_case_    							=				noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

              snake_case_    							=				self.scheduler.step(
                  lowerCAmelCase_						,			timestep=lowerCAmelCase_						,			sample=lowerCAmelCase_						,			).prev_sample

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

        snake_case_    							=				[]
        for i, latent in enumerate(lowerCAmelCase_     ):
              snake_case_    							=				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_     )

        snake_case_    							=				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}'''     )

        snake_case_    							=				images.cpu().numpy()

        if output_type == "pil":
              snake_case_    							=				[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_     )



from __future__ import annotations

import random
import string







class 							lowercase						:




							def __init__(							self  ,A__ = None):
												lowercase		      =		passcode or self.__passcode_creator()
												lowercase		      =		self.__make_key_list()
												lowercase		      =		self.__make_shift_key()




							def __str__(							self):
												return "".join(self.__passcode)




							def 					A__ (							self  ,A__):
												for i in range(1  ,len(A__)  ,2):
																	iterlist[i] *= -1
												return iterlist




							def 					A__ (							self):
												lowercase		      =		string.ascii_letters + string.digits
												lowercase		      =		[random.choice(A__) for _ in range(random.randint(1_0  ,2_0))]
												return password




							def 					A__ (							self):
												lowercase		      =		(
												    string.ascii_letters + string.digits + string.punctuation + ''' \t\n'''
												)

												lowercase		      =		[]

												# creates points known as breakpoints to break the key_list_options at those
												# points and pivot each substring
												lowercase		      =		sorted(set(self.__passcode))
												lowercase		      =		[]

												# algorithm for creating a new shuffled list, keys_l, out of key_list_options
												for i in key_list_options:
																	temp_list.extend(A__)

																	# checking breakpoints at which to pivot temporary sublist and add it into
																	# keys_l
																	if i in breakpoints or i == key_list_options[-1]:
																						keys_l.extend(temp_list[::-1])
																						temp_list.clear()

        # returning a shuffled keys_l to prevent brute force guessing of shift key
												return keys_l




							def 					A__ (							self):
												lowercase		      =		sum(self.__neg_pos([ord(A__) for x in self.__passcode]))
												return num if num > 0 else len(self.__passcode)




							def 					A__ (							self  ,A__):
												lowercase		      =		''''''

												# decoding shift like Caesar cipher algorithm implementing negative shift or
												# reverse shift or left shift
												for i in encoded_message:
																	lowercase		      =		self.__key_list.index(A__)
																	decoded_message += self.__key_list[
																	    (position - self.__shift_key) % -len(self.__key_list)
																	]

												return decoded_message





							def 					A__ (							self  ,A__):
												lowercase		      =		''''''

												# encoding shift like Caesar cipher algorithm implementing positive shift or
												# forward shift or right shift
												for i in plaintext:
																	lowercase		      =		self.__key_list.index(A__)
																	encoded_message += self.__key_list[
																	    (position + self.__shift_key) % len(self.__key_list)
																	]

												return encoded_message



def 			UpperCamelCase       (				lowerCAmelCase__ = "Hello, this is a modified Caesar cipher"						):
					'''simple docstring'''
					lowercase		      =		ShuffledShiftCipher()
					return cipa.decrypt(cipa.encrypt(lowerCAmelCase__						)						)


if __name__ == "__main__":
							import doctest

							doctest.testmod()




