code: 
  
  
  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
  
  
  SCREAMING_SNAKE_CASE__				:    int         =    getLogger(__name__)
  
  
  SCREAMING_SNAKE_CASE__				:    Union[str, Any]         =    4
  SCREAMING_SNAKE_CASE__				:    str         =    7
  
  SCREAMING_SNAKE_CASE__				:    Optional[Any]         =    {
      'float16': torch.floataa,
      'float32': torch.floataa,
  }
  
  
  
  
  def       a__						(		snake_case__				:       Optional[int]    ):
  
  
  
    if isinstance(__A	,      torch.Tensor    ):
      return image
    elif isinstance(__A	,      PIL.Image.Image    ):
      _UpperCAmelCase		:       int       =    [image]
  
    if isinstance(image[0]	,      PIL.Image.Image    ):
      _UpperCAmelCase,_UpperCAmelCase		:       List[str]       =    image[0].size
      _UpperCAmelCase,_UpperCAmelCase		:       int       =    (x - x % 64 for x in (w, h))  # resize to integer multiple of 32
  
      _UpperCAmelCase		:       Union[str, Any]       =    [np.array(i.resize((w, h)    )    )[None, :] for i in image]
      _UpperCAmelCase		:       int       =    np.concatenate(__A	,      axis=0    )
      _UpperCAmelCase		:       Tuple       =    np.array(__A    ).astype(np.floataa    ) / 255.0
      _UpperCAmelCase		:       str       =    image.transpose(0	,      3	,      1	,      2    )
      _UpperCAmelCase		:       Any       =    2.0 * image - 1.0
      _UpperCAmelCase		:       Tuple       =    torch.from_numpy(__A    )
    elif isinstance(image[0]	,      torch.Tensor    ):
      _UpperCAmelCase		:       Any       =    torch.cat(__A	,      dim=0    )
  
    return image
  
  
  
  
  
  class 		_SCREAMING_SNAKE_CASE    (	UpperCAmelCase_    ):
  
  
       def __init__(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_ = 3_50       ,				):
         super().__init__(
             vae=A_       ,				text_encoder=A_       ,				tokenizer=A_       ,				unet=A_       ,				low_res_scheduler=A_       ,				scheduler=A_       ,				safety_checker=A_       ,				feature_extractor=A_       ,				watermarker=A_       ,				max_noise_level=A_       ,				)
  
  
       def __call__(     self       ,				A_       ,				A_       ,				A_ = 75       ,				A_ = 9.0       ,				A_ = 20       ,				A_ = None       ,				A_ = 1       ,				A_ = 0.0       ,				A_ = None       ,				A_ = None       ,				A_ = None       ,				A_ = None       ,				A_ = "pil"       ,				A_ = True       ,				A_ = None       ,				A_ = 1       ,				):
         self.check_inputs(A_       ,				A_       ,				A_       ,				A_						)
  
         # 2. Define call parameters
         if prompt is not None and isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       List[Any]       =    1
         elif prompt is not None and isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       Union[str, Any]       =    len(A_						)
         else:
           _UpperCAmelCase		:       Any       =    prompt_embeds.shape[0]
  
         _UpperCAmelCase		:       List[Any]       =    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		:       List[str]       =    guidance_scale > 1.0
  
         # 3. Encode input prompt
         _UpperCAmelCase		:       Union[str, Any]       =    self._encode_prompt(
             A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				prompt_embeds=A_       ,				negative_prompt_embeds=A_       ,				)
  
         _UpperCAmelCase		:       Dict       =    ORT_TO_PT_TYPE[str(text_embeddings.dtype						)]
  
         # 4. Preprocess image
         _UpperCAmelCase		:       List[Any]       =    preprocess(A_						)
         _UpperCAmelCase		:       Any       =    image.cpu()
  
         # 5. set timesteps
         self.scheduler.set_timesteps(A_       ,				device=A_						)
         _UpperCAmelCase		:       Tuple       =    self.scheduler.timesteps
  
         # 5. Add noise to image
         _UpperCAmelCase		:       str       =    torch.tensor([noise_level]       ,				dtype=torch.long       ,				device=A_						)
         _UpperCAmelCase		:       str       =    torch.randn(image.shape       ,				generator=A_       ,				device=A_       ,				dtype=A_						)
         _UpperCAmelCase		:       List[Any]       =    self.low_res_scheduler.add_noise(A_       ,				A_       ,				A_						)
  
         _UpperCAmelCase		:       str       =    2 if do_classifier_free_guidance else 1
         _UpperCAmelCase		:       int       =    np.concatenate([image] * batch_multiplier * num_images_per_prompt						)
         _UpperCAmelCase		:       Tuple       =    np.concatenate([noise_level] * image.shape[0]						)
  
         # 6. Prepare latent variables
         _UpperCAmelCase,_UpperCAmelCase		:       List[str]       =    image.shape[2:]
         _UpperCAmelCase		:       str       =    self.prepare_latents(
             batch_size * num_images_per_prompt       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				)
  
         # 7. Check that sizes of image and latents match
         _UpperCAmelCase		:       Tuple       =    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		:       List[Any]       =    self.prepare_extra_step_kwargs(A_       ,				A_						)
  
         _UpperCAmelCase		:       List[str]       =    next(
             (input.type for input in self.unet.model.get_inputs() if input.name == """timestep""")       ,				"""tensor(float)"""						)
         _UpperCAmelCase		:       Any       =    ORT_TO_NP_TYPE[timestep_dtype]
  
         # 9. Denoising loop
         _UpperCAmelCase		:       Union[str, Any]       =    len(A_						) - num_inference_steps * self.scheduler.order
         with self.progress_bar(total=A_						) as progress_bar:
           for i, t in enumerate(A_						):
             # expand the latents if we are doing classifier free guidance
             _UpperCAmelCase		:       Optional[int]       =    np.concatenate([latents] * 2						) if do_classifier_free_guidance else latents
  
             # concat latents, mask, masked_image_latents in the channel dimension
             _UpperCAmelCase		:       Optional[Any]       =    self.scheduler.scale_model_input(A_       ,				A_						)
             _UpperCAmelCase		:       List[str]       =    np.concatenate([latent_model_input, image]       ,				axis=1						)
  
             # timestep to tensor
             _UpperCAmelCase		:       Union[str, Any]       =    np.array([t]       ,				dtype=A_						)
  
             # predict the noise residual
             _UpperCAmelCase		:       str       =    self.unet(
                 sample=A_       ,				timestep=A_       ,				encoder_hidden_states=A_       ,				class_labels=noise_level.astype(np.intaa						)       ,				)[0]
  
             # perform guidance
             if do_classifier_free_guidance:
               _UpperCAmelCase,_UpperCAmelCase		:       Tuple       =    np.split(A_       ,				2						)
             _UpperCAmelCase		:       Optional[Any]       =    noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
  
             # compute the previous noisy sample x_t -> x_t-1
             _UpperCAmelCase		:       Any       =    self.scheduler.step(
                 torch.from_numpy(A_						)       ,				A_       ,				A_       ,				**A_						).prev_sample
  
             # call the callback, if provided
             if i == len(A_						) - 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(A_       ,				A_       ,				A_						)
  
                   # 10. Post-processing
         _UpperCAmelCase		:       List[Any]       =    self.decode_latents(latents.float()						)
  
         # 11. Convert to PIL
         if output_type == "pil":
           _UpperCAmelCase		:       Optional[Any]       =    self.numpy_to_pil(A_						)
  
         if not return_dict:
           return (image,)
  
         return ImagePipelineOutput(images=A_						)
  
  
       def 					__snake_case(     self       ,				A_						):
         _UpperCAmelCase		:       Any       =    1 / 0.0_8_3_3_3 * latents
         _UpperCAmelCase		:       List[str]       =    self.vae(latent_sample=A_						)[0]
         _UpperCAmelCase		:       List[Any]       =    np.clip(image / 2 + 0.5       ,				0       ,				1						)
         _UpperCAmelCase		:       int       =    image.transpose((0, 2, 3, 1)						)
         return image
  
  
  
  
       def 					__snake_case(     self       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_       ,				A_ = None       ,				A_ = None       ,				):
         if prompt is not None and isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       Dict       =    1
         elif prompt is not None and isinstance(A_       ,				A_						):
           _UpperCAmelCase		:       Tuple       =    len(A_						)
         else:
           _UpperCAmelCase		:       Dict       =    prompt_embeds.shape[0]
  
         if prompt_embeds is None:
           _UpperCAmelCase		:       str       =    self.tokenizer(
               A_       ,				padding="""max_length"""       ,				max_length=self.tokenizer.model_max_length       ,				truncation=A_       ,				return_tensors="""pt"""       ,				)
           _UpperCAmelCase		:       str       =    text_inputs.input_ids
           _UpperCAmelCase		:       Dict       =    self.tokenizer(A_       ,				padding="""longest"""       ,				return_tensors="""pt"""						).input_ids
  
           if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
               A_       ,				A_						):
             _UpperCAmelCase		:       Any       =    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		:       Optional[Any]       =    self.text_encoder(
               input_ids=text_input_ids.int().to(A_						)       ,				)
           _UpperCAmelCase		:       List[Any]       =    prompt_embeds[0]
  
         _UpperCAmelCase,_UpperCAmelCase,_UpperCAmelCase		:       str       =    prompt_embeds.shape
         # duplicate text embeddings for each generation per prompt, using mps friendly method
         _UpperCAmelCase		:       List[Any]       =    prompt_embeds.repeat(1       ,				A_						)
         _UpperCAmelCase		:       Any       =    prompt_embeds.reshape(bs_embed * num_images_per_prompt       ,				A_       ,				-1						)
  
         # get unconditional embeddings for classifier free guidance
         if do_classifier_free_guidance and negative_prompt_embeds is None:
           _UpperCAmelCase		:       Tuple       =    42
           if negative_prompt is None:
             _UpperCAmelCase		:       Optional[int]       =    [""""""] * batch_size
           elif type(A_						) is not type(A_						):
             raise TypeError(
                 F'''`negative_prompt` should be the same type to `prompt`, but got {type(A_						)} !='''
                 F''' {type(A_						)}.'''						)
           elif isinstance(A_       ,				A_						):
             _UpperCAmelCase		:       List[str]       =    [negative_prompt]
           elif batch_size != len(A_						):
             raise ValueError(
                 F'''`negative_prompt`: {negative_prompt} has batch size {len(A_						)}, but `prompt`:'''
                 F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
                 """ the batch size of `prompt`."""						)
           else:
             _UpperCAmelCase		:       List[Any]       =    negative_prompt
  
           _UpperCAmelCase		:       str       =    text_input_ids.shape[-1]
           _UpperCAmelCase		:       Union[str, Any]       =    self.tokenizer(
               A_       ,				padding="""max_length"""       ,				max_length=A_       ,				truncation=A_       ,				return_tensors="""pt"""       ,				)
  
           # if hasattr(uncond_input, "attention_mask"):
           #     attention_mask = uncond_input.attention_mask.to(device)
           # else:
           #     attention_mask = None
  
           _UpperCAmelCase		:       int       =    self.text_encoder(
               input_ids=uncond_input.input_ids.int().to(A_						)       ,				)
           _UpperCAmelCase		:       Optional[int]       =    uncond_embeddings[0]
  
         if do_classifier_free_guidance:
           _UpperCAmelCase		:       List[str]       =    uncond_embeddings.shape[1]
           # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
           _UpperCAmelCase		:       List[Any]       =    uncond_embeddings.repeat(1       ,				A_						)
           _UpperCAmelCase		:       Tuple       =    uncond_embeddings.reshape(batch_size * num_images_per_prompt       ,				A_       ,				-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		:       int       =    np.concatenate([uncond_embeddings, prompt_embeds]						)
  
         return prompt_embeds
  
  
  
  
  
  
style_context: 
  
  
  import os
  from shutil import copyfile
  from typing import List, Optional, Tuple
  
  from ...tokenization_utils import AddedToken
  from ...tokenization_utils_fast import PreTrainedTokenizerFast
  from ...utils import is_sentencepiece_available, logging
  
  
  if is_sentencepiece_available():
   from .tokenization_xlm_roberta import XLMRobertaTokenizer
  else:
   SCREAMING_SNAKE_CASE__				:    Optional[Any]         =    None
  
  
  SCREAMING_SNAKE_CASE__				:    Dict         =    logging.get_logger(__name__)
  
  SCREAMING_SNAKE_CASE__				:    List[Any]         =    {'vocab_file': 'sentencepiece.bpe.model', 'tokenizer_file': 'tokenizer.json'}
  
  SCREAMING_SNAKE_CASE__				:    Any         =    {
      'vocab_file': {
          'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/sentencepiece.bpe.model',
          'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/sentencepiece.bpe.model',
          'xlm-roberta-large-finetuned-conll02-dutch': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/sentencepiece.bpe.model'
          ),
          'xlm-roberta-large-finetuned-conll02-spanish': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/sentencepiece.bpe.model'
          ),
          'xlm-roberta-large-finetuned-conll03-english': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/sentencepiece.bpe.model'
          ),
          'xlm-roberta-large-finetuned-conll03-german': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/sentencepiece.bpe.model'
          ),
      },
      'tokenizer_file': {
          'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/tokenizer.json',
          'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/tokenizer.json',
          'xlm-roberta-large-finetuned-conll02-dutch': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/tokenizer.json'
          ),
          'xlm-roberta-large-finetuned-conll02-spanish': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/tokenizer.json'
          ),
          'xlm-roberta-large-finetuned-conll03-english': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/tokenizer.json'
          ),
          'xlm-roberta-large-finetuned-conll03-german': (
              'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/tokenizer.json'
          ),
      },
  }
  
  SCREAMING_SNAKE_CASE__				:    Optional[int]         =    {
      'xlm-roberta-base': 512,
      'xlm-roberta-large': 512,
      'xlm-roberta-large-finetuned-conll02-dutch': 512,
      'xlm-roberta-large-finetuned-conll02-spanish': 512,
      'xlm-roberta-large-finetuned-conll03-english': 512,
      'xlm-roberta-large-finetuned-conll03-german': 512,
  }
  
  
  class 		_SCREAMING_SNAKE_CASE    (	A    ):
       __SCREAMING_SNAKE_CASE    				=						VOCAB_FILES_NAMES
       __SCREAMING_SNAKE_CASE    				=						PRETRAINED_VOCAB_FILES_MAP
       __SCREAMING_SNAKE_CASE    				=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __SCREAMING_SNAKE_CASE    				=						['''input_ids''', '''attention_mask''']
       __SCREAMING_SNAKE_CASE    				=						XLMRobertaTokenizer
  
  
       def __init__(     self       ,				A_=None       ,				A_=None       ,				A_="<s>"       ,				A_="</s>"       ,				A_="</s>"       ,				A_="<s>"       ,				A_="<unk>"       ,				A_="<pad>"       ,				A_="<mask>"       ,				**A_       ,				):
         # Mask token behave like a normal word, i.e. include the space before it
         _UpperCAmelCase		:       int       =    AddedToken(A_       ,				lstrip=A_       ,				rstrip=A_						) if isinstance(A_       ,				A_						) else mask_token
  
         super().__init__(
             A_       ,				tokenizer_file=A_       ,				bos_token=A_       ,				eos_token=A_       ,				sep_token=A_       ,				cls_token=A_       ,				unk_token=A_       ,				pad_token=A_       ,				mask_token=A_       ,				**A_       ,				)
  
         _UpperCAmelCase		:       Union[str, Any]       =    vocab_file
         _UpperCAmelCase		:       List[str]       =    False if not self.vocab_file else True
  
  
       def 					__snake_case(     self       ,				A_       ,				A_ = None						):
  
         if token_ids_a is None:
           return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         _UpperCAmelCase		:       Optional[Any]       =    [self.cls_token_id]
         _UpperCAmelCase		:       Union[str, Any]       =    [self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep
  
  
       def 					__snake_case(     self       ,				A_       ,				A_ = None						):
         _UpperCAmelCase		:       Tuple       =    [self.sep_token_id]
         _UpperCAmelCase		:       Optional[int]       =    [self.cls_token_id]
  
         if token_ids_a is None:
           return len(cls + token_ids_a + sep						) * [0]
         return len(cls + token_ids_a + sep + sep + token_ids_a + sep						) * [0]
  
  
  
  
       def 					__snake_case(     self       ,				A_       ,				A_ = None						):
         if not self.can_save_slow_tokenizer:
           raise ValueError(
               """Your fast tokenizer does not have the necessary information to save the vocabulary for a slow """
               """tokenizer."""						)
  
         if not os.path.isdir(A_						):
           logger.error(F'''Vocabulary path ({save_directory}) should be a directory.'''						)
           return
         _UpperCAmelCase		:       List[str]       =    os.path.join(
             A_       ,				(filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]						)
  
         if os.path.abspath(self.vocab_file						) != os.path.abspath(A_						):
           copyfile(self.vocab_file       ,				A_						)
  
         return (out_vocab_file,)
  
  
  
  
  
  