'''simple docstring'''

from logging import getLogger
from typing import Any, Callable, List, Optional, Union

import numpy as np
import PIL
import torch

from ...schedulers import DDPMScheduler
from ..onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
from ..pipeline_utils import ImagePipelineOutput
from . import StableDiffusionUpscalePipeline


__snake_case       :   str  		=    getLogger(__name__)


__snake_case       :   int  		=    4
__snake_case       :   Dict  		=    7

__snake_case       :   Optional[int]  		=    {
    'float16': torch.floataa,
    'float32': torch.floataa,
}



def lowerCamelCase__						(       A_       ):
 if isinstance(UpperCamelCase__       ,			torch.Tensor       ):
  return image
 elif isinstance(UpperCamelCase__       ,			PIL.Image.Image       ):
  UpperCAmelCase_				       =					[image]

 if isinstance(image[0]       ,			PIL.Image.Image       ):
  UpperCAmelCase_				       =					image[0].size
  UpperCAmelCase_				       =					(x - x % 64 for x in (w, h))  # resize to integer multiple of 32

  UpperCAmelCase_				       =					[np.array(i.resize((w, h)       )       )[None, :] for i in image]
  UpperCAmelCase_				       =					np.concatenate(UpperCamelCase__       ,			axis=0       )
  UpperCAmelCase_				       =					np.array(UpperCamelCase__       ).astype(np.floataa       ) / 255.0
  UpperCAmelCase_				       =					image.transpose(0       ,			3       ,			1       ,			2       )
  UpperCAmelCase_				       =					2.0 * image - 1.0
  UpperCAmelCase_				       =					torch.from_numpy(UpperCamelCase__       )
 elif isinstance(image[0]       ,			torch.Tensor       ):
  UpperCAmelCase_				       =					torch.cat(UpperCamelCase__       ,			dim=0       )

 return image


class 							lowercase_    (     _A						):







    def __init__(	self       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__ = 3_5_0       ,     )				->       Any:





     """simple docstring"""

     super().__init__(
         vae=UpperCamelCase__       ,     text_encoder=UpperCamelCase__       ,     tokenizer=UpperCamelCase__       ,     unet=UpperCamelCase__       ,     low_res_scheduler=UpperCamelCase__       ,     scheduler=UpperCamelCase__       ,     safety_checker=UpperCamelCase__       ,     feature_extractor=UpperCamelCase__       ,     watermarker=UpperCamelCase__       ,     max_noise_level=UpperCamelCase__       ,     )







    def __call__(	self       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__ = 7_5       ,     UpperCamelCase__ = 9.0       ,     UpperCamelCase__ = 2_0       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = 1       ,     UpperCamelCase__ = 0.0       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = "pil"       ,     UpperCamelCase__ = True       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = 1       ,     )				->       Optional[Any]:





     """simple docstring"""

     self.check_inputs(UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__				)

     # 2. Define call parameters
     if prompt is not None and isinstance(UpperCamelCase__       ,     UpperCamelCase__				):
      UpperCAmelCase_				       =					1
     elif prompt is not None and isinstance(UpperCamelCase__       ,     UpperCamelCase__				):
      UpperCAmelCase_				       =					len(UpperCamelCase__				)
     else:
      UpperCAmelCase_				       =					prompt_embeds.shape[0]

     UpperCAmelCase_				       =					self._execution_device
     # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
     # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
     # corresponds to doing no classifier free guidance.
     UpperCAmelCase_				       =					guidance_scale > 1.0

     # 3. Encode input prompt
     UpperCAmelCase_				       =					self._encode_prompt(
         UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     prompt_embeds=UpperCamelCase__       ,     negative_prompt_embeds=UpperCamelCase__       ,     )

     UpperCAmelCase_				       =					ORT_TO_PT_TYPE[str(text_embeddings.dtype				)]

     # 4. Preprocess image
     UpperCAmelCase_				       =					preprocess(UpperCamelCase__				)
     UpperCAmelCase_				       =					image.cpu()

     # 5. set timesteps
     self.scheduler.set_timesteps(UpperCamelCase__       ,     device=UpperCamelCase__				)
     UpperCAmelCase_				       =					self.scheduler.timesteps

     # 5. Add noise to image
     UpperCAmelCase_				       =					torch.tensor([noise_level]       ,     dtype=torch.long       ,     device=UpperCamelCase__				)
     UpperCAmelCase_				       =					torch.randn(image.shape       ,     generator=UpperCamelCase__       ,     device=UpperCamelCase__       ,     dtype=UpperCamelCase__				)
     UpperCAmelCase_				       =					self.low_res_scheduler.add_noise(UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__				)

     UpperCAmelCase_				       =					2 if do_classifier_free_guidance else 1
     UpperCAmelCase_				       =					np.concatenate([image] * batch_multiplier * num_images_per_prompt				)
     UpperCAmelCase_				       =					np.concatenate([noise_level] * image.shape[0]				)

     # 6. Prepare latent variables
     UpperCAmelCase_				       =					image.shape[2:]
     UpperCAmelCase_				       =					self.prepare_latents(
         batch_size * num_images_per_prompt       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     )

     # 7. Check that sizes of image and latents match
     UpperCAmelCase_				       =					image.shape[1]
     if NUM_LATENT_CHANNELS + num_channels_image != NUM_UNET_INPUT_CHANNELS:
      raise ValueError(
          "Incorrect configuration settings! The config of `pipeline.unet` expects"
          F""" {NUM_UNET_INPUT_CHANNELS} but received `num_channels_latents`: {NUM_LATENT_CHANNELS} +"""
          F""" `num_channels_image`: {num_channels_image} """
          F""" = {NUM_LATENT_CHANNELS+num_channels_image}. Please verify the config of"""
          " `pipeline.unet` or your `image` input."				)

     # 8. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
     UpperCAmelCase_				       =					self.prepare_extra_step_kwargs(UpperCamelCase__       ,     UpperCamelCase__				)

     UpperCAmelCase_				       =					next(
         (input.type for input in self.unet.model.get_inputs() if input.name == "timestep")       ,     "tensor(float)"				)
     UpperCAmelCase_				       =					ORT_TO_NP_TYPE[timestep_dtype]

     # 9. Denoising loop
     UpperCAmelCase_				       =					len(UpperCamelCase__				) - num_inference_steps * self.scheduler.order
     with self.progress_bar(total=UpperCamelCase__				) as progress_bar:
      for i, t in enumerate(UpperCamelCase__				):
       # expand the latents if we are doing classifier free guidance
       UpperCAmelCase_				       =					np.concatenate([latents] * 2				) if do_classifier_free_guidance else latents

       # concat latents, mask, masked_image_latents in the channel dimension
       UpperCAmelCase_				       =					self.scheduler.scale_model_input(UpperCamelCase__       ,     UpperCamelCase__				)
       UpperCAmelCase_				       =					np.concatenate([latent_model_input, image]       ,     axis=1				)

       # timestep to tensor
       UpperCAmelCase_				       =					np.array([t]       ,     dtype=UpperCamelCase__				)

       # predict the noise residual
       UpperCAmelCase_				       =					self.unet(
           sample=UpperCamelCase__       ,     timestep=UpperCamelCase__       ,     encoder_hidden_states=UpperCamelCase__       ,     class_labels=noise_level.astype(np.intaa				)       ,     )[0]

       # perform guidance
       if do_classifier_free_guidance:
        UpperCAmelCase_				       =					np.split(UpperCamelCase__       ,     2				)
       UpperCAmelCase_				       =					noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)

       # compute the previous noisy sample x_t -> x_t-1
       UpperCAmelCase_				       =					self.scheduler.step(
           torch.from_numpy(UpperCamelCase__				)       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     **UpperCamelCase__				).prev_sample

       # call the callback, if provided
       if i == len(UpperCamelCase__				) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
        progress_bar.update()
        if callback is not None and i % callback_steps == 0:
         callback(UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__				)

        # 10. Post-processing
     UpperCAmelCase_				       =					self.decode_latents(latents.float()				)

     # 11. Convert to PIL
     if output_type == "pil":
      UpperCAmelCase_				       =					self.numpy_to_pil(UpperCamelCase__				)

     if not return_dict:
      return (image,)

     return ImagePipelineOutput(images=UpperCamelCase__				)







    def   lowerCamelCase_    (	self       ,     UpperCamelCase__				)				->       str:





     """simple docstring"""

     UpperCAmelCase_				       =					1 / 0.08333 * latents
     UpperCAmelCase_				       =					self.vae(latent_sample=UpperCamelCase__				)[0]
     UpperCAmelCase_				       =					np.clip(image / 2 + 0.5       ,     0       ,     1				)
     UpperCAmelCase_				       =					image.transpose((0, 2, 3, 1)				)
     return image







    def   lowerCamelCase_    (	self       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__       ,     UpperCamelCase__ = None       ,     UpperCamelCase__ = None       ,     )				->       Any:





     """simple docstring"""

     if prompt is not None and isinstance(UpperCamelCase__       ,     UpperCamelCase__				):
      UpperCAmelCase_				       =					1
     elif prompt is not None and isinstance(UpperCamelCase__       ,     UpperCamelCase__				):
      UpperCAmelCase_				       =					len(UpperCamelCase__				)
     else:
      UpperCAmelCase_				       =					prompt_embeds.shape[0]

     if prompt_embeds is None:
      UpperCAmelCase_				       =					self.tokenizer(
          UpperCamelCase__       ,     padding="max_length"       ,     max_length=self.tokenizer.model_max_length       ,     truncation=UpperCamelCase__       ,     return_tensors="pt"       ,     )
      UpperCAmelCase_				       =					text_inputs.input_ids
      UpperCAmelCase_				       =					self.tokenizer(UpperCamelCase__       ,     padding="longest"       ,     return_tensors="pt"				).input_ids

      if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
          UpperCamelCase__       ,     UpperCamelCase__				):
       UpperCAmelCase_				       =					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}"""				)

      # no positional arguments to text_encoder
      UpperCAmelCase_				       =					self.text_encoder(
          input_ids=text_input_ids.int().to(UpperCamelCase__				)       ,     )
      UpperCAmelCase_				       =					prompt_embeds[0]

     UpperCAmelCase_				       =					prompt_embeds.shape
     # duplicate text embeddings for each generation per prompt, using mps friendly method
     UpperCAmelCase_				       =					prompt_embeds.repeat(1       ,     UpperCamelCase__				)
     UpperCAmelCase_				       =					prompt_embeds.reshape(bs_embed * num_images_per_prompt       ,     UpperCamelCase__       ,     -1				)

     # get unconditional embeddings for classifier free guidance
     if do_classifier_free_guidance and negative_prompt_embeds is None:
      UpperCAmelCase_				       =					42
      if negative_prompt is None:
       UpperCAmelCase_				       =					[''''''] * batch_size
      elif type(UpperCamelCase__				) is not type(UpperCamelCase__				):
       raise TypeError(
           F"""`negative_prompt` should be the same type to `prompt`, but got {type(UpperCamelCase__				)} !="""
           F""" {type(UpperCamelCase__				)}."""				)
      elif isinstance(UpperCamelCase__       ,     UpperCamelCase__				):
       UpperCAmelCase_				       =					[negative_prompt]
      elif batch_size != len(UpperCamelCase__				):
       raise ValueError(
           F"""`negative_prompt`: {negative_prompt} has batch size {len(UpperCamelCase__				)}, but `prompt`:"""
           F""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"""
           " the batch size of `prompt`."				)
      else:
       UpperCAmelCase_				       =					negative_prompt

      UpperCAmelCase_				       =					text_input_ids.shape[-1]
      UpperCAmelCase_				       =					self.tokenizer(
          UpperCamelCase__       ,     padding="max_length"       ,     max_length=UpperCamelCase__       ,     truncation=UpperCamelCase__       ,     return_tensors="pt"       ,     )

      # if hasattr(uncond_input, "attention_mask"):
      #     attention_mask = uncond_input.attention_mask.to(device)
      # else:
      #     attention_mask = None

      UpperCAmelCase_				       =					self.text_encoder(
          input_ids=uncond_input.input_ids.int().to(UpperCamelCase__				)       ,     )
      UpperCAmelCase_				       =					uncond_embeddings[0]

     if do_classifier_free_guidance:
      UpperCAmelCase_				       =					uncond_embeddings.shape[1]
      # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
      UpperCAmelCase_				       =					uncond_embeddings.repeat(1       ,     UpperCamelCase__				)
      UpperCAmelCase_				       =					uncond_embeddings.reshape(batch_size * num_images_per_prompt       ,     UpperCamelCase__       ,     -1				)

      # 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_				       =					np.concatenate([uncond_embeddings, prompt_embeds]				)

     return prompt_embeds

'''simple docstring'''

import os
import sys

from . import rsa_key_generator as rkg

__snake_case       :   Dict  		=    1_28
__snake_case       :   Union[str, Any]  		=    2_56



def lowerCamelCase__						(       A_       ,			A_ = DEFAULT_BLOCK_SIZE       ):
 UpperCAmelCase_				       =					message.encode("ascii"       )

 UpperCAmelCase_				       =					[]
 for block_start in range(0       ,			len(A_       )       ,			A_       ):
  UpperCAmelCase_				       =					0
  for i in range(A_       ,			min(block_start + block_size       ,			len(A_       )       )       ):
   block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
  block_ints.append(A_       )
 return block_ints



def lowerCamelCase__						(       A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ):
 UpperCAmelCase_				       =					[]
 for block_int in block_ints:
  UpperCAmelCase_				       =					[]
  for i in range(block_size - 1       ,			-1       ,			-1       ):
   if len(A_       ) + i < message_length:
    UpperCAmelCase_				       =					block_int // (BYTE_SIZE**i)
    UpperCAmelCase_				       =					block_int % (BYTE_SIZE**i)
    block_message.insert(0       ,			chr(A_       )       )
  message.extend(A_       )
 return "".join(A_       )



def lowerCamelCase__						(       A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ):
 UpperCAmelCase_				       =					[]
 UpperCAmelCase_       ,       UpperCAmelCase_				       =					key

 for block in get_blocks_from_text(A_       ,			A_       ):
  encrypted_blocks.append(pow(A_       ,			A_       ,			A_       )       )
 return encrypted_blocks



def lowerCamelCase__						(       A_       ,			A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ,			):
 UpperCAmelCase_				       =					[]
 UpperCAmelCase_       ,       UpperCAmelCase_				       =					key
 for block in encrypted_blocks:
  decrypted_blocks.append(pow(A_       ,			A_       ,			A_       )       )
 return get_text_from_blocks(A_       ,			A_       ,			A_       )



def lowerCamelCase__						(       A_       ):
 with open(A_       ) as fo:
  UpperCAmelCase_				       =					fo.read()
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					content.split(","       )
 return (int(A_       ), int(A_       ), int(A_       ))



def lowerCamelCase__						(       A_       ,			A_       ,			A_       ,			A_ = DEFAULT_BLOCK_SIZE       ,			):
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					read_key_file(A_       )
 if key_size < block_size * 8:
  sys.exit(
      "ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
      "requires the block size to be equal to or greater than the key size. "
      "Either decrease the block size or use different keys.".format(
          block_size * 8       ,			A_       )       )

 UpperCAmelCase_				       =					[str(A_       ) for i in encrypt_message(A_       ,			(n, e)       ,			A_       )]

 UpperCAmelCase_				       =					",".join(A_       )
 UpperCAmelCase_				       =					F"""{len(A_       )}_{block_size}_{encrypted_content}"""
 with open(A_       ,			"w"       ) as fo:
  fo.write(A_       )
 return encrypted_content



def lowerCamelCase__						(       A_       ,			A_       ):
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					read_key_file(A_       )
 with open(A_       ) as fo:
  UpperCAmelCase_				       =					fo.read()
 UpperCAmelCase_       ,       UpperCAmelCase_       ,       UpperCAmelCase_				       =					content.split("_"       )
 UpperCAmelCase_				       =					int(A_       )
 UpperCAmelCase_				       =					int(A_       )

 if key_size < block_size * 8:
  sys.exit(
      "ERROR: Block size is {} bits and key size is {} bits. The RSA cipher "
      "requires the block size to be equal to or greater than the key size. "
      "Did you specify the correct key file and encrypted file?".format(
          block_size * 8       ,			A_       )       )

 UpperCAmelCase_				       =					[]
 for block in encrypted_message.split(","       ):
  encrypted_blocks.append(int(A_       )       )

 return decrypt_message(A_       ,			A_       ,			(n, d)       ,			A_       )



def lowerCamelCase__						(       ):
 UpperCAmelCase_				       =					"encrypted_file.txt"
 UpperCAmelCase_				       =					input(R"Encrypt\Decrypt [e\d]: "       )

 if response.lower().startswith("e"       ):
  UpperCAmelCase_				       =					"encrypt"
 elif response.lower().startswith("d"       ):
  UpperCAmelCase_				       =					"decrypt"

 if mode == "encrypt":
  if not os.path.exists("rsa_pubkey.txt"       ):
   rkg.make_key_files("rsa"       ,			1_024       )

  UpperCAmelCase_				       =					input("\nEnter message: "       )
  UpperCAmelCase_				       =					"rsa_pubkey.txt"
  print(F"""Encrypting and writing to {filename}..."""       )
  UpperCAmelCase_				       =					encrypt_and_write_to_file(A_       ,			A_       ,			A_       )

  print("\nEncrypted text:"       )
  print(A_       )

 elif mode == "decrypt":
  UpperCAmelCase_				       =					"rsa_privkey.txt"
  print(F"""Reading from {filename} and decrypting..."""       )
  UpperCAmelCase_				       =					read_from_file_and_decrypt(A_       ,			A_       )
  print("writing decryption to rsa_decryption.txt..."       )
  with open("rsa_decryption.txt"       ,			"w"       ) as dec:
   dec.write(A_       )

  print("\nDecryption:"       )
  print(A_       )


if __name__ == "__main__":
      main()
