


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

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .attention import BasicTransformerBlock
from .attention_processor import AttentionProcessor, AttnProcessor
from .embeddings import TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin



@dataclass
class 							A   (	UpperCAmelCase__							):
					'''simple docstring'''






					A__      =			42






class 							A   (	UpperCAmelCase__			,  UpperCAmelCase__							):
					'''simple docstring'''






					@register_to_config
					def __init__(self   :						Any				, _UpperCAmelCase   :						int = 32				, _UpperCAmelCase   :						int = 64				, _UpperCAmelCase   :						int = 20				, _UpperCAmelCase   :						int = 768				, _UpperCAmelCase   :						Any=77				, _UpperCAmelCase   :						List[str]=4				, _UpperCAmelCase   :						float = 0.0				, _UpperCAmelCase   :						str = "silu"				, _UpperCAmelCase   :						Optional[str] = None				, _UpperCAmelCase   :						Optional[str] = None				, _UpperCAmelCase   :						Optional[str] = "linear"				, _UpperCAmelCase   :						Optional[str] = "prd"				, _UpperCAmelCase   :						Optional[int] = None				, _UpperCAmelCase   :						Optional[int] = None				, _UpperCAmelCase   :						Optional[int] = None				, )						->       List[Any]:




							"""simple docstring"""


							super().__init__()
							lowercase__					      =		num_attention_heads
							lowercase__					      =		attention_head_dim
							lowercase__					      =		num_attention_heads * attention_head_dim
							lowercase__					      =		additional_embeddings

							lowercase__					      =		time_embed_dim or inner_dim
							lowercase__					      =		embedding_proj_dim or embedding_dim
							lowercase__					      =		clip_embed_dim or embedding_dim

							lowercase__					      =		Timesteps(_UpperCAmelCase				, _UpperCAmelCase				, 0		)
							lowercase__					      =		TimestepEmbedding(_UpperCAmelCase				, _UpperCAmelCase				, out_dim=_UpperCAmelCase				, act_fn=_UpperCAmelCase		)

							lowercase__					      =		nn.Linear(_UpperCAmelCase				, _UpperCAmelCase		)

							if embedding_proj_norm_type is None:
									lowercase__					      =		None
							elif embedding_proj_norm_type == "layer":
									lowercase__					      =		nn.LayerNorm(_UpperCAmelCase		)
							else:
									raise ValueError(f'''unsupported embedding_proj_norm_type: {embedding_proj_norm_type}'''		)

							lowercase__					      =		nn.Linear(_UpperCAmelCase				, _UpperCAmelCase		)

							if encoder_hid_proj_type is None:
									lowercase__					      =		None
							elif encoder_hid_proj_type == "linear":
									lowercase__					      =		nn.Linear(_UpperCAmelCase				, _UpperCAmelCase		)
							else:
									raise ValueError(f'''unsupported encoder_hid_proj_type: {encoder_hid_proj_type}'''		)

							lowercase__					      =		nn.Parameter(torch.zeros(1				, num_embeddings + additional_embeddings				, _UpperCAmelCase		)		)

							if added_emb_type == "prd":
									lowercase__					      =		nn.Parameter(torch.zeros(1				, 1				, _UpperCAmelCase		)		)
							elif added_emb_type is None:
									lowercase__					      =		None
							else:
									raise ValueError(
									    f'''`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `\'prd\'` or `None`.'''		)

							lowercase__					      =		nn.ModuleList(
							    [
							        BasicTransformerBlock(
							            _UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase				, dropout=_UpperCAmelCase				, activation_fn="""gelu"""				, attention_bias=_UpperCAmelCase				, )
							        for d in range(_UpperCAmelCase		)
							    ]		)

							if norm_in_type == "layer":
									lowercase__					      =		nn.LayerNorm(_UpperCAmelCase		)
							elif norm_in_type is None:
									lowercase__					      =		None
							else:
									raise ValueError(f'''Unsupported norm_in_type: {norm_in_type}.'''		)

							lowercase__					      =		nn.LayerNorm(_UpperCAmelCase		)

							lowercase__					      =		nn.Linear(_UpperCAmelCase				, _UpperCAmelCase		)

							lowercase__					      =		torch.full(
							    [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings]				, -10_000.0		)
							causal_attention_mask.triu_(1		)
							lowercase__					      =		causal_attention_mask[None, ...]
							self.register_buffer("""causal_attention_mask"""				, _UpperCAmelCase				, persistent=_UpperCAmelCase		)

							lowercase__					      =		nn.Parameter(torch.zeros(1				, _UpperCAmelCase		)		)
							lowercase__					      =		nn.Parameter(torch.zeros(1				, _UpperCAmelCase		)		)

					@property
					# Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
					def   lowerCamelCase__					(self   :						Tuple		)						->       Dict[str, AttentionProcessor]:




							"""simple docstring"""


							lowercase__					      =		{}

							def fn_recursive_add_processors(_UpperCAmelCase   :						str				, _UpperCAmelCase   :						torch.nn.Module				, _UpperCAmelCase   :						Dict[str, AttentionProcessor]		):
									if hasattr(_UpperCAmelCase				, """set_processor"""		):
											lowercase__					      =		module.processor

									for sub_name, child in module.named_children():
											fn_recursive_add_processors(f'''{name}.{sub_name}'''				, _UpperCAmelCase				, _UpperCAmelCase		)

									return processors

							for name, module in self.named_children():
									fn_recursive_add_processors(_UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase		)

							return processors

					def   lowerCamelCase__					(self   :						Tuple				, _UpperCAmelCase   :						Union[AttentionProcessor, Dict[str, AttentionProcessor]]		)						->       Optional[Any]:




							"""simple docstring"""


							lowercase__					      =		len(self.attn_processors.keys()		)

							if isinstance(_UpperCAmelCase				, _UpperCAmelCase		) and len(_UpperCAmelCase		) != count:
									raise ValueError(
									    f'''A dict of processors was passed, but the number of processors {len(_UpperCAmelCase		)} does not match the'''
									    f''' number of attention layers: {count}. Please make sure to pass {count} processor classes.'''		)

							def fn_recursive_attn_processor(_UpperCAmelCase   :						str				, _UpperCAmelCase   :						torch.nn.Module				, _UpperCAmelCase   :						Optional[Any]		):
									if hasattr(_UpperCAmelCase				, """set_processor"""		):
											if not isinstance(_UpperCAmelCase				, _UpperCAmelCase		):
													module.set_processor(_UpperCAmelCase		)
											else:
													module.set_processor(processor.pop(f'''{name}.processor'''		)		)

									for sub_name, child in module.named_children():
											fn_recursive_attn_processor(f'''{name}.{sub_name}'''				, _UpperCAmelCase				, _UpperCAmelCase		)

							for name, module in self.named_children():
									fn_recursive_attn_processor(_UpperCAmelCase				, _UpperCAmelCase				, _UpperCAmelCase		)

					def   lowerCamelCase__					(self   :						Any		)						->       List[str]:




							"""simple docstring"""


							self.set_attn_processor(AttnProcessor()		)

					def   lowerCamelCase__					(self   :						int				, _UpperCAmelCase   :						Optional[int]				, _UpperCAmelCase   :						Union[torch.Tensor, float, int]				, _UpperCAmelCase   :						torch.FloatTensor				, _UpperCAmelCase   :						Optional[torch.FloatTensor] = None				, _UpperCAmelCase   :						Optional[torch.BoolTensor] = None				, _UpperCAmelCase   :						bool = True				, )						->       Optional[Any]:




							"""simple docstring"""


							lowercase__					      =		hidden_states.shape[0]

							lowercase__					      =		timestep
							if not torch.is_tensor(_UpperCAmelCase		):
									lowercase__					      =		torch.tensor([timesteps]				, dtype=torch.long				, device=hidden_states.device		)
							elif torch.is_tensor(_UpperCAmelCase		) and len(timesteps.shape		) == 0:
									lowercase__					      =		timesteps[None].to(hidden_states.device		)

							# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
							lowercase__					      =		timesteps * torch.ones(_UpperCAmelCase				, dtype=timesteps.dtype				, device=timesteps.device		)

							lowercase__					      =		self.time_proj(_UpperCAmelCase		)

							# timesteps does not contain any weights and will always return f32 tensors
							# but time_embedding might be fp16, so we need to cast here.
							lowercase__					      =		timesteps_projected.to(dtype=self.dtype		)
							lowercase__					      =		self.time_embedding(_UpperCAmelCase		)

							if self.embedding_proj_norm is not None:
									lowercase__					      =		self.embedding_proj_norm(_UpperCAmelCase		)

							lowercase__					      =		self.embedding_proj(_UpperCAmelCase		)
							if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
									lowercase__					      =		self.encoder_hidden_states_proj(_UpperCAmelCase		)
							elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
									raise ValueError("""`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set"""		)

							lowercase__					      =		self.proj_in(_UpperCAmelCase		)

							lowercase__					      =		self.positional_embedding.to(hidden_states.dtype		)

							lowercase__					      =		[]
							lowercase__					      =		0

							if encoder_hidden_states is not None:
									additional_embeds.append(_UpperCAmelCase		)
									additional_embeddings_len += encoder_hidden_states.shape[1]

							if len(proj_embeddings.shape		) == 2:
									lowercase__					      =		proj_embeddings[:, None, :]

							if len(hidden_states.shape		) == 2:
									lowercase__					      =		hidden_states[:, None, :]

							lowercase__					      =		additional_embeds + [
							    proj_embeddings,
							    time_embeddings[:, None, :],
							    hidden_states,
							]

							if self.prd_embedding is not None:
									lowercase__					      =		self.prd_embedding.to(hidden_states.dtype		).expand(_UpperCAmelCase				, -1				, -1		)
									additional_embeds.append(_UpperCAmelCase		)

							lowercase__					      =		torch.cat(
							    _UpperCAmelCase				, dim=1				, )

							# Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
							lowercase__					      =		additional_embeddings_len + proj_embeddings.shape[1] + 1
							if positional_embeddings.shape[1] < hidden_states.shape[1]:
									lowercase__					      =		F.pad(
									    _UpperCAmelCase				, (
									        0,
									        0,
									        additional_embeddings_len,
									        self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
									    )				, value=0.0				, )

							lowercase__					      =		hidden_states + positional_embeddings

							if attention_mask is not None:
									lowercase__					      =		(1 - attention_mask.to(hidden_states.dtype		)) * -10_000.0
									lowercase__					      =		F.pad(_UpperCAmelCase				, (0, self.additional_embeddings)				, value=0.0		)
									lowercase__					      =		(attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype		)
									lowercase__					      =		attention_mask.repeat_interleave(self.config.num_attention_heads				, dim=0		)

							if self.norm_in is not None:
									lowercase__					      =		self.norm_in(_UpperCAmelCase		)

							for block in self.transformer_blocks:
									lowercase__					      =		block(_UpperCAmelCase				, attention_mask=_UpperCAmelCase		)

							lowercase__					      =		self.norm_out(_UpperCAmelCase		)

							if self.prd_embedding is not None:
									lowercase__					      =		hidden_states[:, -1]
							else:
									lowercase__					      =		hidden_states[:, additional_embeddings_len:]

							lowercase__					      =		self.proj_to_clip_embeddings(_UpperCAmelCase		)

							if not return_dict:
									return (predicted_image_embedding,)

							return PriorTransformerOutput(predicted_image_embedding=_UpperCAmelCase		)


					def   lowerCamelCase__					(self   :						Optional[int]				, _UpperCAmelCase   :						Any		)						->       Union[str, Any]:




							"""simple docstring"""


							lowercase__					      =		(prior_latents * self.clip_std) + self.clip_mean
							return prior_latents





A	:		Tuple    =       'ABCDEFGHIJKLMNOPQRSTUVWXYZ'






def 			UpperCamelCase (     )       ->  None:
		"""simple docstring"""




		lowercase__					      =		input("""Enter message: """					)
		lowercase__					      =		input("""Enter key [alphanumeric]: """					)
		lowercase__					      =		input("""Encrypt/Decrypt [e/d]: """					)

		if mode.lower().startswith("""e"""					):
				lowercase__					      =		"""encrypt"""
				lowercase__					      =		encrypt_message(__magic_name__   ,   __magic_name__					)
		elif mode.lower().startswith("""d"""					):
				lowercase__					      =		"""decrypt"""
				lowercase__					      =		decrypt_message(__magic_name__   ,   __magic_name__					)

		print(f'''\n{mode.title()}ed message:'''					)
		print(__magic_name__					)






def 			UpperCamelCase (     __magic_name__					:							str   ,   __magic_name__					:							str					)       ->  str:
		"""simple docstring"""




		return translate_message(__magic_name__   ,   __magic_name__   ,   """encrypt"""					)






def 			UpperCamelCase (     __magic_name__					:							str   ,   __magic_name__					:							str					)       ->  str:
		"""simple docstring"""




		return translate_message(__magic_name__   ,   __magic_name__   ,   """decrypt"""					)






def 			UpperCamelCase (     __magic_name__					:							str   ,   __magic_name__					:							str   ,   __magic_name__					:							str					)       ->  str:
		"""simple docstring"""




		lowercase__					      =		[]
		lowercase__					      =		0
		lowercase__					      =		key.upper()

		for symbol in message:
				lowercase__					      =		LETTERS.find(symbol.upper()					)
				if num != -1:
						if mode == "encrypt":
								num += LETTERS.find(key[key_index]					)
						elif mode == "decrypt":
								num -= LETTERS.find(key[key_index]					)

						num %= len(__magic_name__					)

						if symbol.isupper():
								translated.append(LETTERS[num]					)
						elif symbol.islower():
								translated.append(LETTERS[num].lower()					)

						key_index += 1
						if key_index == len(__magic_name__					):
								lowercase__					      =		0
				else:
						translated.append(__magic_name__					)
		return "".join(__magic_name__					)


if __name__ == "__main__":
	main()

