






'''simple docstring'''
import json
import os
import unittest

from transformers import CLIPTokenizer, CLIPTokenizerFast
from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
from transformers.testing_utils import require_ftfy, require_tokenizers

from ...test_tokenization_common import TokenizerTesterMixin


@require_tokenizers
class        _UpperCAmelCase						(		snake_case				,					unittest.TestCase			):
    __lowerCamelCase:   str		       =    CLIPTokenizer
    __lowerCamelCase:   Dict		       =    CLIPTokenizerFast
    __lowerCamelCase:   Union[str, Any]		       =    True
    __lowerCamelCase:   Dict		       =    {}
    __lowerCamelCase:   Any		       =    False




    def 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






       super().setUp()

       # fmt: off
       lowercase_	:    int           =     ["l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"]
       # fmt: on
       lowercase_	:    Tuple           =     dict(zip(a  ,     range(len(a			)			)			)			)
       lowercase_	:    Dict           =     ["#version: 0.2", "l o", "lo w</w>", "e r</w>"]
       lowercase_	:    List[str]           =     {"unk_token": "<unk>"}

       lowercase_	:    int           =     os.path.join(self.tmpdirname  ,     VOCAB_FILES_NAMES["vocab_file"]			)
       lowercase_	:    Dict           =     os.path.join(self.tmpdirname  ,     VOCAB_FILES_NAMES["merges_file"]			)
       with open(self.vocab_file  ,     "w"  ,     encoding="utf-8"			) as fp:
          fp.write(json.dumps(a			) + "\n"			)
       with open(self.merges_file  ,     "w"  ,     encoding="utf-8"			) as fp:
          fp.write("\n".join(a			)			)




    def 				lowerCAmelCase__				(			self  :       str  ,     **a  :       List[Any]			):






       '''simple docstring'''






       kwargs.update(self.special_tokens_map			)
       return CLIPTokenizer.from_pretrained(self.tmpdirname  ,     **a			)




    def 				lowerCAmelCase__				(			self  :       Any  ,     **a  :       List[str]			):






       '''simple docstring'''






       kwargs.update(self.special_tokens_map			)
       return CLIPTokenizerFast.from_pretrained(self.tmpdirname  ,     **a			)




    def 				lowerCAmelCase__				(			self  :       Optional[Any]  ,     a  :       Dict			):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     "lower newer"
       lowercase_	:    Any           =     "lower newer"
       return input_text, output_text




    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       lowercase_	:    Dict           =     CLIPTokenizer(self.vocab_file  ,     self.merges_file  ,     **self.special_tokens_map			)
       lowercase_	:    Optional[int]           =     "lower newer"
       lowercase_	:    Any           =     ["lo", "w", "er</w>", "n", "e", "w", "er</w>"]
       lowercase_	:    str           =     tokenizer.tokenize(a			)
       self.assertListEqual(a  ,     a			)

       lowercase_	:    str           =     tokens + [tokenizer.unk_token]
       lowercase_	:    str           =     [1_0, 2, 1_6, 9, 3, 2, 1_6, 2_0]
       self.assertListEqual(tokenizer.convert_tokens_to_ids(a			)  ,     a			)




    @require_ftfy
    def 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
          with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""			):
             lowercase_	:    Union[str, Any]           =     self.tokenizer_class.from_pretrained(a  ,     **a			)
             lowercase_	:    Union[str, Any]           =     self.rust_tokenizer_class.from_pretrained(a  ,     **a			)

             lowercase_	:    Optional[int]           =     "A\n'll 11p223RF☆ho!!to?'d'd''d of a cat to-$''d."
             lowercase_	:    Optional[int]           =     tokenizer_s.tokenize(a			)
             lowercase_	:    List[Any]           =     tokenizer_r.tokenize(a			)

             self.assertListEqual(a  ,     a			)

             # Test that the tokenization is identical on an example containing a character (Latin Small Letter A
             # with Tilde) encoded in 2 different ways
             lowercase_	:    Optional[Any]           =     "xa\u0303y" + " " + "x\xe3y"
             lowercase_	:    int           =     tokenizer_s.tokenize(a			)
             lowercase_	:    Optional[Any]           =     tokenizer_r.tokenize(a			)

             self.assertListEqual(a  ,     a			)

             # Test that the tokenization is identical on unicode of space type
             lowercase_	:    str           =     [
                 "\u0009",  # (horizontal tab, '\t')
                 "\u000B",  # (vertical tab)
                 "\u000C",  # (form feed)
                 "\u0020",  # (space, ' ')
                 "\u200E",  # (left-to-right mark):w
                 "\u200F",  # (right-to-left mark)
             ]
             for unicode_seq in spaces_unicodes:
                lowercase_	:    Optional[int]           =     tokenizer_s.tokenize(a			)
                lowercase_	:    Dict           =     tokenizer_r.tokenize(a			)

                self.assertListEqual(a  ,     a			)

             # Test that the tokenization is identical on unicode of line break type
             lowercase_	:    str           =     [
                 "\u000A",  # (line feed, '\n')
                 "\r\n",  # (carriage return and line feed, '\r\n')
                 "\u000D",  # (carriage return, '\r')
                 "\r",  # (carriage return, '\r')
                 "\u000D",  # (carriage return, '\r')
                 "\u2028",  # (line separator)
                 "\u2029",  # (paragraph separator)
                 # "\u0085", # (next line)
             ]

             # The tokenization is not identical for the character "\u0085" (next line). The slow version using ftfy transforms
             # it into the Horizontal Ellipsis character "…" ("\u2026") while the fast version transforms it into a
             # space (and thus into an empty list).

             for unicode_seq in line_break_unicodes:
                lowercase_	:    Tuple           =     tokenizer_s.tokenize(a			)
                lowercase_	:    Optional[Any]           =     tokenizer_r.tokenize(a			)

                self.assertListEqual(a  ,     a			)




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]			):






       '''simple docstring'''






       for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
          with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})"""			):
             lowercase_	:    Tuple           =     "hello"  # `hello` is a token in the vocabulary of `pretrained_name`
             lowercase_	:    Union[str, Any]           =     f"""{text_of_1_token} {text_of_1_token}"""

             lowercase_	:    Dict           =     self.rust_tokenizer_class.from_pretrained(
                 a  ,     use_fast=a  ,     )
             lowercase_	:    Optional[Any]           =     tokenizer_r(a  ,     return_offsets_mapping=a  ,     add_special_tokens=a			)
             self.assertEqual(encoding.offset_mapping[0]  ,     (0, len(a			))			)
             self.assertEqual(
                 encoding.offset_mapping[1]  ,     (len(a			) + 1, len(a			) + 1 + len(a			))  ,     )

             lowercase_	:    Any           =     f""" {text}"""

             lowercase_	:    Optional[int]           =     self.rust_tokenizer_class.from_pretrained(
                 a  ,     use_fast=a  ,     )
             lowercase_	:    Tuple           =     tokenizer_r(a  ,     return_offsets_mapping=a  ,     add_special_tokens=a			)
             self.assertEqual(encoding.offset_mapping[0]  ,     (1, 1 + len(a			))			)
             self.assertEqual(
                 encoding.offset_mapping[1]  ,     (1 + len(a			) + 1, 1 + len(a			) + 1 + len(a			))  ,     )




    def 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






       with self.assertRaises(a			) as context:
          self.rust_tokenizer_class.from_pretrained("robot-test/old-clip-tokenizer"			)

       self.assertTrue(
           context.exception.args[0].startswith(
               "The `backend_tokenizer` provided does not match the expected format."			)			)




    @require_ftfy
    def 				lowerCAmelCase__				(			self  :       Optional[Any]			):






       '''simple docstring'''






       super().test_tokenization_python_rust_equals()





    def 				lowerCAmelCase__				(			self  :       List[Any]			):






       '''simple docstring'''






       pass












'''simple docstring'''
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from PIL import Image

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,
)


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

UpperCamelCase__ =			'\n    Examples:\n        ```py\n        >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n        >>> from diffusers.utils import load_image\n        >>> import torch\n\n        >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-prior", torch_dtype=torch.float16\n        ... )\n        >>> pipe_prior.to("cuda")\n\n        >>> prompt = "A red cartoon frog, 4k"\n        >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n        >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n        ...     "kandinsky-community/kandinsky-2-2-decoder", torch_dtype=torch.float16\n        ... )\n        >>> pipe.to("cuda")\n\n        >>> init_image = load_image(\n        ...     "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"\n        ...     "/kandinsky/frog.png"\n        ... )\n\n        >>> image = pipe(\n        ...     image=init_image,\n        ...     image_embeds=image_emb,\n        ...     negative_image_embeds=zero_image_emb,\n        ...     height=768,\n        ...     width=768,\n        ...     num_inference_steps=100,\n        ...     strength=0.2,\n        ... ).images\n\n        >>> image[0].save("red_frog.png")\n        ```\n'




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase						,		_UpperCamelCase=8							):


   """simple docstring"""




   lowercase_	:    Union[str, Any]           =     height // scale_factor**2
   if height % scale_factor**2 != 0:
      new_height += 1
   lowercase_	:    Union[str, Any]           =     width // scale_factor**2
   if width % scale_factor**2 != 0:
      new_width += 1
   return new_height * scale_factor, new_width * scale_factor




def 		__SCREAMING_SNAKE_CASE					(  _UpperCamelCase						,		_UpperCamelCase=512						,		_UpperCamelCase=512							):


   """simple docstring"""




   lowercase_	:    Union[str, Any]           =     pil_image.resize((w, h)						,		resample=Image.BICUBIC						,		reducing_gap=1							)
   lowercase_	:    str           =     np.array(pil_image.convert("RGB"							)							)
   lowercase_	:    Optional[int]           =     arr.astype(np.floataa							) / 127.5 - 1
   lowercase_	:    int           =     np.transpose(_UpperCamelCase						,		[2, 0, 1]							)
   lowercase_	:    str           =     torch.from_numpy(_UpperCamelCase							).unsqueeze(0							)
   return image





class        _UpperCAmelCase						(		snake_case			):




    def __init__(			self  :       List[Any]  ,     a  :       UNetaDConditionModel  ,     a  :       DDPMScheduler  ,     a  :       VQModel  ,     ):






       '''simple docstring'''






       super().__init__()

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




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       Tuple  ,     a  :       List[str]  ,     a  :       List[Any]			):






       '''simple docstring'''






       lowercase_	:    Dict           =     min(int(num_inference_steps * strength			)  ,     a			)

       lowercase_	:    str           =     max(num_inference_steps - init_timestep  ,     0			)
       lowercase_	:    Tuple           =     self.scheduler.timesteps[t_start:]

       return timesteps, num_inference_steps - t_start




    def 				lowerCAmelCase__				(			self  :       Union[str, Any]  ,     a  :       int  ,     a  :       List[Any]  ,     a  :       Tuple  ,     a  :       Union[str, Any]  ,     a  :       int  ,     a  :       Tuple  ,     a  :       Optional[Any]=None			):






       '''simple docstring'''






       if not isinstance(a  ,     (torch.Tensor, PIL.Image.Image, list)			):
          raise ValueError(
              f"""`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(a			)}"""			)

       lowercase_	:    str           =     image.to(device=a  ,     dtype=a			)

       lowercase_	:    Any           =     batch_size * num_images_per_prompt

       if image.shape[1] == 4:
          lowercase_	:    str           =     image

       else:
          if isinstance(a  ,     a			) and len(a			) != batch_size:
             raise ValueError(
                 f"""You have passed a list of generators of length {len(a			)}, but requested an effective batch"""
                 f""" size of {batch_size}. Make sure the batch size matches the length of the generators."""			)

          elif isinstance(a  ,     a			):
             lowercase_	:    str           =     [
                 self.movq.encode(image[i : i + 1]			).latent_dist.sample(generator[i]			) for i in range(a			)
             ]
             lowercase_	:    List[Any]           =     torch.cat(a  ,     dim=0			)
          else:
             lowercase_	:    Tuple           =     self.movq.encode(a			).latent_dist.sample(a			)

          lowercase_	:    Union[str, Any]           =     self.movq.config.scaling_factor * init_latents

       lowercase_	:    Tuple           =     torch.cat([init_latents]  ,     dim=0			)

       lowercase_	:    List[Any]           =     init_latents.shape
       lowercase_	:    Union[str, Any]           =     randn_tensor(a  ,     generator=a  ,     device=a  ,     dtype=a			)

       # get latents
       lowercase_	:    Dict           =     self.scheduler.add_noise(a  ,     a  ,     a			)

       lowercase_	:    Tuple           =     init_latents

       return latents




    def 				lowerCAmelCase__				(			self  :       List[Any]  ,     a  :       str=0			):






       '''simple docstring'''






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

       lowercase_	:    Optional[Any]           =     torch.device(f"""cuda:{gpu_id}"""			)

       lowercase_	:    Optional[Any]           =     [
           self.unet,
           self.movq,
       ]
       for cpu_offloaded_model in models:
          if cpu_offloaded_model is not None:
             cpu_offload(a  ,     a			)




    def 				lowerCAmelCase__				(			self  :       Optional[int]  ,     a  :       Union[str, Any]=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."			)

       lowercase_	:    Any           =     torch.device(f"""cuda:{gpu_id}"""			)

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

       lowercase_	:    Optional[int]           =     None
       for cpu_offloaded_model in [self.unet, self.movq]:
          lowercase_    ,		lowercase_	:    Union[str, Any]           =     cpu_offload_with_hook(a  ,     a  ,     prev_module_hook=a			)

       # We'll offload the last model manually.
       lowercase_	:    List[Any]           =     hook




    @property
    # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
    def 				lowerCAmelCase__				(			self  :       int			):






       '''simple docstring'''






       if not hasattr(self.unet  ,     "_hf_hook"			):
          return self.device
       for module in self.unet.modules():
          if (
              hasattr(a  ,     "_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(a			)
    def __call__(			self  :       Optional[int]  ,     a  :       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,     a  :       Union[torch.FloatTensor, PIL.Image.Image, List[torch.FloatTensor], List[PIL.Image.Image]]  ,     a  :       Union[torch.FloatTensor, List[torch.FloatTensor]]  ,     a  :       int = 5_1_2  ,     a  :       int = 5_1_2  ,     a  :       int = 1_0_0  ,     a  :       float = 4.0  ,     a  :       float = 0.3  ,     a  :       int = 1  ,     a  :       Optional[Union[torch.Generator, List[torch.Generator]]] = None  ,     a  :       Optional[str] = "pil"  ,     a  :       bool = True  ,     ):






       '''simple docstring'''






       lowercase_	:    Optional[int]           =     self._execution_device

       lowercase_	:    Dict           =     guidance_scale > 1.0

       if isinstance(a  ,     a			):
          lowercase_	:    Dict           =     torch.cat(a  ,     dim=0			)
       lowercase_	:    Dict           =     image_embeds.shape[0]
       if isinstance(a  ,     a			):
          lowercase_	:    str           =     torch.cat(a  ,     dim=0			)

       if do_classifier_free_guidance:
          lowercase_	:    Optional[Any]           =     image_embeds.repeat_interleave(a  ,     dim=0			)
          lowercase_	:    int           =     negative_image_embeds.repeat_interleave(a  ,     dim=0			)

       lowercase_	:    int           =     torch.cat([negative_image_embeds, image_embeds]  ,     dim=0			).to(dtype=self.unet.dtype  ,     device=a			)

       if not isinstance(a  ,     a			):
          lowercase_	:    List[Any]           =     [image]
       if not all(isinstance(a  ,     (PIL.Image.Image, torch.Tensor)			) for i in image			):
          raise ValueError(
              f"""Input is in incorrect format: {[type(a			) for i in image]}. Currently, we only support  PIL image and pytorch tensor"""			)

       lowercase_	:    List[Any]           =     torch.cat([prepare_image(a  ,     a  ,     a			) for i in image]  ,     dim=0			)
       lowercase_	:    List[Any]           =     image.to(dtype=image_embeds.dtype  ,     device=a			)

       lowercase_	:    Optional[int]           =     self.movq.encode(a			)["latents"]
       lowercase_	:    Dict           =     latents.repeat_interleave(a  ,     dim=0			)
       self.scheduler.set_timesteps(a  ,     device=a			)
       lowercase_    ,		lowercase_	:    List[Any]           =     self.get_timesteps(a  ,     a  ,     a			)
       lowercase_	:    Tuple           =     timesteps[:1].repeat(batch_size * num_images_per_prompt			)
       lowercase_    ,		lowercase_	:    Optional[Any]           =     downscale_height_and_width(a  ,     a  ,     self.movq_scale_factor			)
       lowercase_	:    Tuple           =     self.prepare_latents(
           a  ,     a  ,     a  ,     a  ,     image_embeds.dtype  ,     a  ,     a			)
       for i, t in enumerate(self.progress_bar(a			)			):
          # expand the latents if we are doing classifier free guidance
          lowercase_	:    Tuple           =     torch.cat([latents] * 2			) if do_classifier_free_guidance else latents

          lowercase_	:    int           =     {"image_embeds": image_embeds}
          lowercase_	:    Optional[int]           =     self.unet(
              sample=a  ,     timestep=a  ,     encoder_hidden_states=a  ,     added_cond_kwargs=a  ,     return_dict=a  ,     )[0]

          if do_classifier_free_guidance:
             lowercase_    ,		lowercase_	:    List[Any]           =     noise_pred.split(latents.shape[1]  ,     dim=1			)
             lowercase_    ,		lowercase_	:    int           =     noise_pred.chunk(2			)
             lowercase_    ,		lowercase_	:    Any           =     variance_pred.chunk(2			)
             lowercase_	:    Dict           =     noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
             lowercase_	:    Optional[Any]           =     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"]
          ):
             lowercase_    ,		lowercase_	:    List[Any]           =     noise_pred.split(latents.shape[1]  ,     dim=1			)

          # compute the previous noisy sample x_t -> x_t-1
          lowercase_	:    Dict           =     self.scheduler.step(
              a  ,     a  ,     a  ,     generator=a  ,     )[0]

       # post-processing
       lowercase_	:    Optional[Any]           =     self.movq.decode(a  ,     force_not_quantize=a			)["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"]:
          lowercase_	:    Tuple           =     image * 0.5 + 0.5
          lowercase_	:    Any           =     image.clamp(0  ,     1			)
          lowercase_	:    Any           =     image.cpu().permute(0  ,     2  ,     3  ,     1			).float().numpy()

       if output_type == "pil":
          lowercase_	:    Tuple           =     self.numpy_to_pil(a			)

       if not return_dict:
          return (image,)

       return ImagePipelineOutput(images=a			)




