


'''simple docstring'''



from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


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





class        UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  : Tuple												=      ['safety_checker', 'feature_extractor']







    def __init__(							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = True      ,					)    ->					Optional[int]:
         super().__init__()
         if hasattr(scheduler.config      ,					'steps_offset'     ) and scheduler.config.steps_offset != 1:
              __lowerCamelCase       :     int        =		(
                  f'The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`'
                  f' should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure '
                  'to update the config accordingly as leaving `steps_offset` might led to incorrect results'
                  ' in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,'
                  ' it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`'
                  ' file'
              )
              deprecate('steps_offset!=1'      ,					'1.0.0'      ,					SCREAMING_SNAKE_CASE_      ,					standard_warn=SCREAMING_SNAKE_CASE_     )
              __lowerCamelCase       :     Dict        =		dict(scheduler.config     )
              __lowerCamelCase       :     Optional[int]        =		1
              __lowerCamelCase       :     Tuple        =		FrozenDict(SCREAMING_SNAKE_CASE_     )

         self.register_modules(
             vae=SCREAMING_SNAKE_CASE_      ,					text_encoder=SCREAMING_SNAKE_CASE_      ,					tokenizer=SCREAMING_SNAKE_CASE_      ,					unet=SCREAMING_SNAKE_CASE_      ,					scheduler=SCREAMING_SNAKE_CASE_      ,					safety_checker=SCREAMING_SNAKE_CASE_      ,					feature_extractor=SCREAMING_SNAKE_CASE_      ,					)
         self.register_to_config(requires_safety_checker=SCREAMING_SNAKE_CASE_     )







    @property
    def 				lowercase_    (							self     )    ->					Dict[str, Any]:
         return {k: getattr(self      ,					SCREAMING_SNAKE_CASE_     ) for k in self.config.keys() if not k.startswith('_'     )}







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_ = "auto"     )    ->					Optional[int]:
         if slice_size == "auto":
              # half the attention head size is usually a good trade-off between
              # speed and memory
              __lowerCamelCase       :     Any        =		self.unet.config.attention_head_dim // 2
         self.unet.set_attention_slice(SCREAMING_SNAKE_CASE_     )







    def 				lowercase_    (							self     )    ->					List[str]:
         self.enable_attention_slicing(SCREAMING_SNAKE_CASE_     )







    @torch.no_grad()
    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = 0.8      ,					SCREAMING_SNAKE_CASE_ = 50      ,					SCREAMING_SNAKE_CASE_ = 7.5      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					SCREAMING_SNAKE_CASE_ = 0.0      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = "pil"      ,					SCREAMING_SNAKE_CASE_ = True      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					)    ->					List[Any]:
         # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
         return StableDiffusionInpaintPipelineLegacy(**self.components     )(
             prompt=SCREAMING_SNAKE_CASE_      ,					image=SCREAMING_SNAKE_CASE_      ,					mask_image=SCREAMING_SNAKE_CASE_      ,					strength=SCREAMING_SNAKE_CASE_      ,					num_inference_steps=SCREAMING_SNAKE_CASE_      ,					guidance_scale=SCREAMING_SNAKE_CASE_      ,					negative_prompt=SCREAMING_SNAKE_CASE_      ,					num_images_per_prompt=SCREAMING_SNAKE_CASE_      ,					eta=SCREAMING_SNAKE_CASE_      ,					generator=SCREAMING_SNAKE_CASE_      ,					output_type=SCREAMING_SNAKE_CASE_      ,					return_dict=SCREAMING_SNAKE_CASE_      ,					callback=SCREAMING_SNAKE_CASE_      ,					)







    @torch.no_grad()
    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = 0.8      ,					SCREAMING_SNAKE_CASE_ = 50      ,					SCREAMING_SNAKE_CASE_ = 7.5      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					SCREAMING_SNAKE_CASE_ = 0.0      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = "pil"      ,					SCREAMING_SNAKE_CASE_ = True      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					**SCREAMING_SNAKE_CASE_      ,					)    ->					Union[str, Any]:
         # For more information on how this function works, please see: https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionImg2ImgPipeline
         return StableDiffusionImgaImgPipeline(**self.components     )(
             prompt=SCREAMING_SNAKE_CASE_      ,					image=SCREAMING_SNAKE_CASE_      ,					strength=SCREAMING_SNAKE_CASE_      ,					num_inference_steps=SCREAMING_SNAKE_CASE_      ,					guidance_scale=SCREAMING_SNAKE_CASE_      ,					negative_prompt=SCREAMING_SNAKE_CASE_      ,					num_images_per_prompt=SCREAMING_SNAKE_CASE_      ,					eta=SCREAMING_SNAKE_CASE_      ,					generator=SCREAMING_SNAKE_CASE_      ,					output_type=SCREAMING_SNAKE_CASE_      ,					return_dict=SCREAMING_SNAKE_CASE_      ,					callback=SCREAMING_SNAKE_CASE_      ,					callback_steps=SCREAMING_SNAKE_CASE_      ,					)







    @torch.no_grad()
    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = 5_12      ,					SCREAMING_SNAKE_CASE_ = 5_12      ,					SCREAMING_SNAKE_CASE_ = 50      ,					SCREAMING_SNAKE_CASE_ = 7.5      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					SCREAMING_SNAKE_CASE_ = 0.0      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = "pil"      ,					SCREAMING_SNAKE_CASE_ = True      ,					SCREAMING_SNAKE_CASE_ = None      ,					SCREAMING_SNAKE_CASE_ = 1      ,					)    ->					List[str]:
         # For more information on how this function https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion#diffusers.StableDiffusionPipeline
         return StableDiffusionPipeline(**self.components     )(
             prompt=SCREAMING_SNAKE_CASE_      ,					height=SCREAMING_SNAKE_CASE_      ,					width=SCREAMING_SNAKE_CASE_      ,					num_inference_steps=SCREAMING_SNAKE_CASE_      ,					guidance_scale=SCREAMING_SNAKE_CASE_      ,					negative_prompt=SCREAMING_SNAKE_CASE_      ,					num_images_per_prompt=SCREAMING_SNAKE_CASE_      ,					eta=SCREAMING_SNAKE_CASE_      ,					generator=SCREAMING_SNAKE_CASE_      ,					latents=SCREAMING_SNAKE_CASE_      ,					output_type=SCREAMING_SNAKE_CASE_      ,					return_dict=SCREAMING_SNAKE_CASE_      ,					callback=SCREAMING_SNAKE_CASE_      ,					callback_steps=SCREAMING_SNAKE_CASE_      ,					)










'''simple docstring'''



from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


A__		: Optional[int]												=  logging.get_logger(__name__)

A__		: Optional[Any]												=  {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

A__		: Optional[int]												=  {
    """vocab_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """openai/clip-vit-base-patch32""": (
            """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json"""
        ),
    },
}

A__		: Any												=  {
    """openai/clip-vit-base-patch32""": 77,
}





class        UpperCAmelCase_  (_UpperCAmelCase  ):





    """simple docstring"""






    lowerCamelCase  : Union[str, Any]												=      VOCAB_FILES_NAMES
    lowerCamelCase  : Optional[int]												=      PRETRAINED_VOCAB_FILES_MAP
    lowerCamelCase  : str												=      PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    lowerCamelCase  : Union[str, Any]												=      ['input_ids', 'attention_mask']
    lowerCamelCase  : Optional[Any]												=      CLIPTokenizer







    def __init__(							self      ,					SCREAMING_SNAKE_CASE_=None      ,					SCREAMING_SNAKE_CASE_=None      ,					SCREAMING_SNAKE_CASE_=None      ,					SCREAMING_SNAKE_CASE_="<|endoftext|>"      ,					SCREAMING_SNAKE_CASE_="<|startoftext|>"      ,					SCREAMING_SNAKE_CASE_="<|endoftext|>"      ,					SCREAMING_SNAKE_CASE_="<|endoftext|>"      ,					**SCREAMING_SNAKE_CASE_      ,					)    ->					Union[str, Any]:
         super().__init__(
             SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_      ,					tokenizer_file=SCREAMING_SNAKE_CASE_      ,					unk_token=SCREAMING_SNAKE_CASE_      ,					bos_token=SCREAMING_SNAKE_CASE_      ,					eos_token=SCREAMING_SNAKE_CASE_      ,					pad_token=SCREAMING_SNAKE_CASE_      ,					**SCREAMING_SNAKE_CASE_      ,					)

         if not isinstance(self.backend_tokenizer.pre_tokenizer      ,					pre_tokenizers.Sequence     ):
              raise ValueError(
                  'The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'
                  ' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'
                  ' to be compatible with this version.The easiest way to do so is'
                  ' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'
                  ' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'
                  ' transformers.'     )

         self._wrap_decode_method_backend_tokenizer()







    def 				lowercase_    (							self     )    ->					Optional[Any]:
         __lowerCamelCase       :     Union[str, Any]        =		self.backend_tokenizer.decode

         def new_decode_method(*SCREAMING_SNAKE_CASE_      ,					**SCREAMING_SNAKE_CASE_     ):
              __lowerCamelCase       :     int        =		orig_decode_method(*SCREAMING_SNAKE_CASE_      ,					**SCREAMING_SNAKE_CASE_     )
              __lowerCamelCase       :     List[str]        =		text.replace(self.backend_tokenizer.model.end_of_word_suffix      ,					' '     ).strip()
              return text

         __lowerCamelCase       :     Union[str, Any]        =		new_decode_method







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = None     )    ->					List[int]:
         __lowerCamelCase       :     Optional[int]        =		[self.bos_token_id]
         __lowerCamelCase       :     Tuple        =		[self.eos_token_id]

         if token_ids_a is None:
              return bos_token + token_ids_a + eos_token
         return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = None     )    ->					List[int]:
         __lowerCamelCase       :     Dict        =		[self.bos_token_id]
         __lowerCamelCase       :     Optional[Any]        =		[self.eos_token_id]

         if token_ids_a is None:
              return len(bos_token + token_ids_a + eos_token     ) * [0]
         return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token     ) * [0]







    def 				lowercase_    (							self      ,					SCREAMING_SNAKE_CASE_      ,					SCREAMING_SNAKE_CASE_ = None     )    ->					Tuple[str]:
         __lowerCamelCase       :     int        =		self._tokenizer.model.save(SCREAMING_SNAKE_CASE_      ,					name=SCREAMING_SNAKE_CASE_     )
         return tuple(SCREAMING_SNAKE_CASE_     )






