

"""simple docstring"""






from typing import List, Optional, Union

import torch

from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)


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

_lowerCAmelCase						=		"\n    Examples:\n        ```py\n        >>> import torch\n        >>> import numpy as np\n\n        >>> from diffusers import KandinskyV22PriorPipeline, KandinskyV22ControlnetPipeline\n        >>> from transformers import pipeline\n        >>> from diffusers.utils import load_image\n\n\n        >>> def make_hint(image, depth_estimator):\n        ...     image = depth_estimator(image)[\"depth\"]\n        ...     image = np.array(image)\n        ...     image = image[:, :, None]\n        ...     image = np.concatenate([image, image, image], axis=2)\n        ...     detected_map = torch.from_numpy(image).float() / 255.0\n        ...     hint = detected_map.permute(2, 0, 1)\n        ...     return hint\n\n\n        >>> depth_estimator = pipeline(\"depth-estimation\")\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior = pipe_prior.to(\"cuda\")\n\n        >>> pipe = KandinskyV22ControlnetPipeline.from_pretrained(\n        ...     \"kandinsky-community/kandinsky-2-2-controlnet-depth\", torch_dtype=torch.float16\n        ... )\n        >>> pipe = pipe.to(\"cuda\")\n\n\n        >>> img = load_image(\n        ...     \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n        ...     \"/kandinsky/cat.png\"\n        ... ).resize((768, 768))\n\n        >>> hint = make_hint(img, depth_estimator).unsqueeze(0).half().to(\"cuda\")\n\n        >>> prompt = \"A robot, 4k photo\"\n        >>> negative_prior_prompt = \"lowres, text, error, cropped, worst quality, low quality, jpeg artifacts, ugly, duplicate, morbid, mutilated, out of frame, extra fingers, mutated hands, poorly drawn hands, poorly drawn face, mutation, deformed, blurry, dehydrated, bad anatomy, bad proportions, extra limbs, cloned face, disfigured, gross proportions, malformed limbs, missing arms, missing legs, extra arms, extra legs, fused fingers, too many fingers, long neck, username, watermark, signature\"\n\n        >>> generator = torch.Generator(device=\"cuda\").manual_seed(43)\n\n        >>> image_emb, zero_image_emb = pipe_prior(\n        ...     prompt=prompt, negative_prompt=negative_prior_prompt, generator=generator\n        ... ).to_tuple()\n\n        >>> images = pipe(\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     hint=hint,\n        ...     num_inference_steps=50,\n        ...     generator=generator,\n        ...     height=768,\n        ...     width=768,\n        ... ).images\n\n        >>> images[0].save(\"robot_cat.png\")\n        ```\n"

def 		lowerCamelCase__		(					_lowerCamelCase ,   _lowerCamelCase ,   _lowerCamelCase=8   ):

    '''simple docstring'''



    _lowerCAmelCase       :   int  =    height // scale_factor**2
    if height % scale_factor**2 != 0:
        new_height += 1
    _lowerCAmelCase       :   Any  =    width // scale_factor**2
    if width % scale_factor**2 != 0:
        new_width += 1
    return new_height * scale_factor, new_width * scale_factor







class 	__UpperCamelCase    (    _UpperCAmelCase						):

  def __init__(		self    ,_A    ,_A    ,_A    ,):
      '''simple docstring'''

      super().__init__()

      self.register_modules(
          unet=lowerCamelCase_    ,scheduler=lowerCamelCase_    ,movq=lowerCamelCase_    ,)
      _lowerCAmelCase       :   Dict  =    2 ** (len(self.movq.config.block_out_channels      ) - 1)

  def __lowerCamelCase		(		self    ,_A    ,_A    ,_A    ,_A    ,_A    ,_A      ):
      '''simple docstring'''

      if latents is None:
          _lowerCAmelCase       :   List[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}"""      )
          _lowerCAmelCase       :   int  =    latents.to(lowerCamelCase_      )

      _lowerCAmelCase       :   List[str]  =    latents * scheduler.init_noise_sigma
      return latents

  def __lowerCamelCase		(		self    ,_A=0      ):
      '''simple docstring'''

      if is_accelerate_available():
          from accelerate import cpu_offload
      else:
          raise ImportError('Please install accelerate via `pip install accelerate`'      )

      _lowerCAmelCase       :   List[str]  =    torch.device(F"""cuda:{gpu_id}"""      )

      _lowerCAmelCase       :   int  =    [
          self.unet,
          self.movq,
      ]
      for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
              cpu_offload(lowerCamelCase_    ,lowerCamelCase_      )

  def __lowerCamelCase		(		self    ,_A=0      ):
      '''simple docstring'''

      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.'      )

      _lowerCAmelCase       :   Optional[int]  =    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)

      _lowerCAmelCase       :   str  =    None
      for cpu_offloaded_model in [self.unet, self.movq]:
          _lowerCAmelCase       :   List[Any]  =    cpu_offload_with_hook(lowerCamelCase_    ,lowerCamelCase_    ,prev_module_hook=lowerCamelCase_      )

      # We'll offload the last model manually.
      _lowerCAmelCase       :   int  =    hook

  @property
  # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      if not hasattr(self.unet    ,'_hf_hook'      ):
          return self.device
      for module in self.unet.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







  @torch.no_grad()
  @replace_example_docstring(lowerCamelCase_      )
  def __call__(		self    ,_A    ,_A    ,_A    ,_A = 512    ,_A = 512    ,_A = 100    ,_A = 4.0    ,_A = 1    ,_A = None    ,_A = None    ,_A = "pil"    ,_A = True    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Tuple  =    self._execution_device

      _lowerCAmelCase       :   List[Any]  =    guidance_scale > 1.0

      if isinstance(lowerCamelCase_    ,lowerCamelCase_      ):
          _lowerCAmelCase       :   str  =    torch.cat(lowerCamelCase_    ,dim=0      )
      if isinstance(lowerCamelCase_    ,lowerCamelCase_      ):
          _lowerCAmelCase       :   Optional[Any]  =    torch.cat(lowerCamelCase_    ,dim=0      )
      if isinstance(lowerCamelCase_    ,lowerCamelCase_      ):
          _lowerCAmelCase       :   Union[str, Any]  =    torch.cat(lowerCamelCase_    ,dim=0      )

      _lowerCAmelCase       :   List[Any]  =    image_embeds.shape[0] * num_images_per_prompt

      if do_classifier_free_guidance:
          _lowerCAmelCase       :   Tuple  =    image_embeds.repeat_interleave(lowerCamelCase_    ,dim=0      )
          _lowerCAmelCase       :   Optional[Any]  =    negative_image_embeds.repeat_interleave(lowerCamelCase_    ,dim=0      )
          _lowerCAmelCase       :   Tuple  =    hint.repeat_interleave(lowerCamelCase_    ,dim=0      )

      _lowerCAmelCase       :   Any  =    torch.cat([negative_image_embeds, image_embeds]    ,dim=0      ).to(dtype=self.unet.dtype    ,device=lowerCamelCase_      )
      _lowerCAmelCase       :   List[Any]  =    torch.cat([hint, hint]    ,dim=0      ).to(dtype=self.unet.dtype    ,device=lowerCamelCase_      )
      self.scheduler.set_timesteps(lowerCamelCase_    ,device=lowerCamelCase_      )
      _lowerCAmelCase       :   Dict  =    self.scheduler.timesteps

      _lowerCAmelCase       :   List[str]  =    self.movq.config.latent_channels

      _lowerCAmelCase       :   Any  =    downscale_height_and_width(lowerCamelCase_    ,lowerCamelCase_    ,self.movq_scale_factor      )

      # create initial latent
      _lowerCAmelCase       :   int  =    self.prepare_latents(
          (batch_size, num_channels_latents, height, width)    ,image_embeds.dtype    ,lowerCamelCase_    ,lowerCamelCase_    ,lowerCamelCase_    ,self.scheduler    ,)

      for i, t in enumerate(self.progress_bar(lowerCamelCase_      )      ):
          # expand the latents if we are doing classifier free guidance
          _lowerCAmelCase       :   Dict  =    torch.cat([latents] * 2      ) if do_classifier_free_guidance else latents

          _lowerCAmelCase       :   Any  =    {'''image_embeds''': image_embeds, '''hint''': hint}
          _lowerCAmelCase       :   Dict  =    self.unet(
              sample=lowerCamelCase_    ,timestep=lowerCamelCase_    ,encoder_hidden_states=lowerCamelCase_    ,added_cond_kwargs=lowerCamelCase_    ,return_dict=lowerCamelCase_    ,)[0]

          if do_classifier_free_guidance:
              _lowerCAmelCase       :   Any  =    noise_pred.split(latents.shape[1]    ,dim=1      )
              _lowerCAmelCase       :   str  =    noise_pred.chunk(2      )
              _lowerCAmelCase       :   List[Any]  =    variance_pred.chunk(2      )
              _lowerCAmelCase       :   Dict  =    noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
              _lowerCAmelCase       :   str  =    torch.cat([noise_pred, variance_pred_text]    ,dim=1      )

          if not (
              hasattr(self.scheduler.config    ,'variance_type'      )
              and self.scheduler.config.variance_type in ["learned", "learned_range"]
          ):
              _lowerCAmelCase       :   int  =    noise_pred.split(latents.shape[1]    ,dim=1      )

          # compute the previous noisy sample x_t -> x_t-1
          _lowerCAmelCase       :   str  =    self.scheduler.step(
              lowerCamelCase_    ,lowerCamelCase_    ,lowerCamelCase_    ,generator=lowerCamelCase_    ,)[0]
      # post-processing
      _lowerCAmelCase       :   int  =    self.movq.decode(lowerCamelCase_    ,force_not_quantize=lowerCamelCase_      )['''sample''']

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

      if output_type in ["np", "pil"]:
          _lowerCAmelCase       :   Optional[Any]  =    image * 0.5 + 0.5
          _lowerCAmelCase       :   Optional[Any]  =    image.clamp(0    ,1      )
          _lowerCAmelCase       :   str  =    image.cpu().permute(0    ,2    ,3    ,1      ).float().numpy()

      if output_type == "pil":
          _lowerCAmelCase       :   Optional[int]  =    self.numpy_to_pil(lowerCamelCase_      )

      if not return_dict:
          return (image,)

      return ImagePipelineOutput(images=lowerCamelCase_      )









"""simple docstring"""






import os
import unicodedata
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import SPIECE_UNDERLINE, logging


_lowerCAmelCase						=		logging.get_logger(__name__)

_lowerCAmelCase						=		{"""vocab_file""": """spiece.model"""}

_lowerCAmelCase						=		{
    """vocab_file""": {
        """xlnet-base-cased""": """https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model""",
        """xlnet-large-cased""": """https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model""",
    }
}

_lowerCAmelCase						=		{
    """xlnet-base-cased""": None,
    """xlnet-large-cased""": None,
}

# Segments (not really needed)
_lowerCAmelCase						=		0
_lowerCAmelCase						=		1
_lowerCAmelCase						=		2
_lowerCAmelCase						=		3
_lowerCAmelCase						=		4







class 	__UpperCamelCase    (    a__						):
  _UpperCAmelCase          =		VOCAB_FILES_NAMES
  _UpperCAmelCase          =		PRETRAINED_VOCAB_FILES_MAP
  _UpperCAmelCase          =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  _UpperCAmelCase          =		"left"

  def __init__(		self    ,_A    ,_A=False    ,_A=True    ,_A=False    ,_A="<s>"    ,_A="</s>"    ,_A="<unk>"    ,_A="<sep>"    ,_A="<pad>"    ,_A="<cls>"    ,_A="<mask>"    ,_A=["<eop>", "<eod>"]    ,_A = None    ,**_A    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    AddedToken(_A    ,lstrip=_A    ,rstrip=_A      ) if isinstance(_A    ,_A      ) else mask_token

      _lowerCAmelCase       :   Union[str, Any]  =    {} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          do_lower_case=_A    ,remove_space=_A    ,keep_accents=_A    ,bos_token=_A    ,eos_token=_A    ,unk_token=_A    ,sep_token=_A    ,pad_token=_A    ,cls_token=_A    ,mask_token=_A    ,additional_special_tokens=_A    ,sp_model_kwargs=self.sp_model_kwargs    ,**_A    ,)

      _lowerCAmelCase       :   int  =    3

      _lowerCAmelCase       :   Union[str, Any]  =    do_lower_case
      _lowerCAmelCase       :   Dict  =    remove_space
      _lowerCAmelCase       :   int  =    keep_accents
      _lowerCAmelCase       :   List[str]  =    vocab_file

      _lowerCAmelCase       :   List[Any]  =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
      self.sp_model.Load(_A      )

  @property
  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      return len(self.sp_model      )

  def __lowerCamelCase		(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    {self.convert_ids_to_tokens(_A      ): i for i in range(self.vocab_size      )}
      vocab.update(self.added_tokens_encoder      )
      return vocab

  def __getstate__(		self      ):
      '''simple docstring'''

      _lowerCAmelCase       :   List[Any]  =    self.__dict__.copy()
      _lowerCAmelCase       :   List[str]  =    None
      return state

  def __setstate__(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    d

      # for backward compatibility
      if not hasattr(self    ,'sp_model_kwargs'      ):
          _lowerCAmelCase       :   Union[str, Any]  =    {}

      _lowerCAmelCase       :   Optional[Any]  =    spm.SentencePieceProcessor(**self.sp_model_kwargs      )
      self.sp_model.Load(self.vocab_file      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      if self.remove_space:
          _lowerCAmelCase       :   str  =    ' '.join(inputs.strip().split()      )
      else:
          _lowerCAmelCase       :   Dict  =    inputs
      _lowerCAmelCase       :   List[str]  =    outputs.replace('``'    ,'"'      ).replace('\'\''    ,'"'      )

      if not self.keep_accents:
          _lowerCAmelCase       :   Optional[Any]  =    unicodedata.normalize('NFKD'    ,_A      )
          _lowerCAmelCase       :   Dict  =    ''.join([c for c in outputs if not unicodedata.combining(_A      )]      )
      if self.do_lower_case:
          _lowerCAmelCase       :   Tuple  =    outputs.lower()

      return outputs

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Union[str, Any]  =    self.preprocess_text(_A      )
      _lowerCAmelCase       :   int  =    self.sp_model.encode(_A    ,out_type=_A      )
      _lowerCAmelCase       :   int  =    []
      for piece in pieces:
          if len(_A      ) > 1 and piece[-1] == str(','      ) and piece[-2].isdigit():
              _lowerCAmelCase       :   Union[str, Any]  =    self.sp_model.EncodeAsPieces(piece[:-1].replace(_A    ,''      )      )
              if piece[0] != SPIECE_UNDERLINE and cur_pieces[0][0] == SPIECE_UNDERLINE:
                  if len(cur_pieces[0]      ) == 1:
                      _lowerCAmelCase       :   int  =    cur_pieces[1:]
                  else:
                      _lowerCAmelCase       :   Any  =    cur_pieces[0][1:]
              cur_pieces.append(piece[-1]      )
              new_pieces.extend(_A      )
          else:
              new_pieces.append(_A      )

      return new_pieces

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      return self.sp_model.PieceToId(_A      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      return self.sp_model.IdToPiece(_A      )

  def __lowerCamelCase		(		self    ,_A      ):
      '''simple docstring'''

      _lowerCAmelCase       :   Optional[Any]  =    ''.join(_A      ).replace(_A    ,' '      ).strip()
      return out_string

  def __lowerCamelCase		(		self    ,_A    ,_A = False    ,_A = None    ,_A = True    ,**_A    ,):
      '''simple docstring'''

      _lowerCAmelCase       :   Dict  =    kwargs.pop('use_source_tokenizer'    ,_A      )

      _lowerCAmelCase       :   Dict  =    self.convert_ids_to_tokens(_A    ,skip_special_tokens=_A      )

      # To avoid mixing byte-level and unicode for byte-level BPT
      # we need to build string separately for added tokens and byte-level tokens
      # cf. https://github.com/huggingface/transformers/issues/1133
      _lowerCAmelCase       :   Optional[Any]  =    []
      _lowerCAmelCase       :   int  =    []
      for token in filtered_tokens:
          if skip_special_tokens and token in self.all_special_ids:
              continue
          if token in self.added_tokens_encoder:
              if current_sub_text:
                  sub_texts.append(self.convert_tokens_to_string(_A      )      )
                  _lowerCAmelCase       :   Tuple  =    []
              sub_texts.append(_A      )
          else:
              current_sub_text.append(_A      )
      if current_sub_text:
          sub_texts.append(self.convert_tokens_to_string(_A      )      )

      # Mimic the behavior of the Rust tokenizer:
      # By default, there are no spaces between special tokens
      _lowerCAmelCase       :   List[Any]  =    ''.join(_A      )

      _lowerCAmelCase       :   Tuple  =    (
          clean_up_tokenization_spaces
          if clean_up_tokenization_spaces is not None
          else self.clean_up_tokenization_spaces
      )
      if clean_up_tokenization_spaces:
          _lowerCAmelCase       :   int  =    self.clean_up_tokenization(_A      )
          return clean_text
      else:
          return text

  def __lowerCamelCase		(		self    ,_A    ,_A = None      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    [self.sep_token_id]
      _lowerCAmelCase       :   Union[str, Any]  =    [self.cls_token_id]
      if token_ids_a is None:
          return token_ids_a + sep + cls
      return token_ids_a + sep + token_ids_a + sep + cls

  def __lowerCamelCase		(		self    ,_A    ,_A = None    ,_A = False      ):
      '''simple docstring'''

      if already_has_special_tokens:
          return super().get_special_tokens_mask(
              token_ids_a=_A    ,token_ids_a=_A    ,already_has_special_tokens=_A      )

      if token_ids_a is not None:
          return ([0] * len(_A      )) + [1] + ([0] * len(_A      )) + [1, 1]
      return ([0] * len(_A      )) + [1, 1]

  def __lowerCamelCase		(		self    ,_A    ,_A = None      ):
      '''simple docstring'''

      _lowerCAmelCase       :   str  =    [self.sep_token_id]
      _lowerCAmelCase       :   Any  =    [2]

      if token_ids_a is None:
          return len(token_ids_a + sep      ) * [0] + cls_segment_id
      return len(token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1] + cls_segment_id







  def __lowerCamelCase		(		self    ,_A    ,_A = None      ):
      '''simple docstring'''

      if not os.path.isdir(_A      ):
          logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""      )
          return
      _lowerCAmelCase       :   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      ) and os.path.isfile(self.vocab_file      ):
          copyfile(self.vocab_file    ,_A      )
      elif not os.path.isfile(self.vocab_file      ):
          with open(_A    ,'wb'      ) as fi:
              _lowerCAmelCase       :   Optional[Any]  =    self.sp_model.serialized_model_proto()
              fi.write(_A      )

      return (out_vocab_file,)





