





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


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

class     A_ (  lowerCAmelCase_  ):

			'''simple docstring'''





			_lowerCAmelCase						=    ["""safety_checker""", """feature_extractor"""]




			def __init__(					self			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_			,     A_ = True			,     ):
								super().__init__()
								if hasattr(scheduler.config			,     "steps_offset"   ) and scheduler.config.steps_offset != 1:
													_UpperCamelCase											=   (
													    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"			,     A_			,     standard_warn=A_   )
													_UpperCamelCase											=   dict(scheduler.config   )
													_UpperCamelCase											=   1
													_UpperCamelCase											=   FrozenDict(A_   )

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




			@property
			def       a	(					self   ):
								return {k: getattr(self			,     A_   ) for k in self.config.keys() if not k.startswith("_"   )}




			def       a	(					self			,     A_ = "auto"   ):
								if slice_size == "auto":
													# half the attention head size is usually a good trade-off between
													# speed and memory
													_UpperCamelCase											=   self.unet.config.attention_head_dim // 2
								self.unet.set_attention_slice(A_   )




			def       a	(					self   ):
								self.enable_attention_slicing(A_   )




			@torch.no_grad()
			def       a	(					self			,     A_			,     A_			,     A_			,     A_ = 0.8			,     A_ = 50			,     A_ = 7.5			,     A_ = None			,     A_ = 1			,     A_ = 0.0			,     A_ = None			,     A_ = "pil"			,     A_ = True			,     A_ = None			,     A_ = 1			,     ):
								# 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=A_			,     image=A_			,     mask_image=A_			,     strength=A_			,     num_inference_steps=A_			,     guidance_scale=A_			,     negative_prompt=A_			,     num_images_per_prompt=A_			,     eta=A_			,     generator=A_			,     output_type=A_			,     return_dict=A_			,     callback=A_			,     )




			@torch.no_grad()
			def       a	(					self			,     A_			,     A_			,     A_ = 0.8			,     A_ = 50			,     A_ = 7.5			,     A_ = None			,     A_ = 1			,     A_ = 0.0			,     A_ = None			,     A_ = "pil"			,     A_ = True			,     A_ = None			,     A_ = 1			,     **A_			,     ):
								# 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=A_			,     image=A_			,     strength=A_			,     num_inference_steps=A_			,     guidance_scale=A_			,     negative_prompt=A_			,     num_images_per_prompt=A_			,     eta=A_			,     generator=A_			,     output_type=A_			,     return_dict=A_			,     callback=A_			,     callback_steps=A_			,     )




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










'''simple docstring'''



import os
from typing import List, Union

import tensorflow as tf
from tensorflow_text import BertTokenizer as BertTokenizerLayer
from tensorflow_text import FastBertTokenizer, ShrinkLongestTrimmer, case_fold_utfa, combine_segments, pad_model_inputs

from .tokenization_bert import BertTokenizer

class     A_ (  tf.keras.layers.Layer  ):

			'''simple docstring'''





			def __init__(					self			,     A_			,     A_			,     A_ = None			,     A_ = None			,     A_ = None			,     A_ = "longest"			,     A_ = True			,     A_ = 5_12			,     A_ = None			,     A_ = True			,     A_ = True			,     A_ = True			,     **A_			,     ):
								super().__init__()
								if use_fast_bert_tokenizer:
													_UpperCamelCase											=   FastBertTokenizer(
													    A_			,     token_out_type=tf.intaa			,     lower_case_nfd_strip_accents=A_			,     **A_   )
								else:
													_UpperCamelCase											=   tf.lookup.StaticVocabularyTable(
													    tf.lookup.KeyValueTensorInitializer(
													        keys=A_			,     key_dtype=tf.string			,     values=tf.range(tf.size(A_			,     out_type=tf.intaa   )			,     dtype=tf.intaa   )			,     value_dtype=tf.intaa			,     )			,     num_oov_buckets=1			,     )
													_UpperCamelCase											=   BertTokenizerLayer(
													    A_			,     token_out_type=tf.intaa			,     lower_case=A_			,     **A_   )

								_UpperCamelCase											=   vocab_list
								_UpperCamelCase											=   do_lower_case
								_UpperCamelCase											=   cls_token_id or vocab_list.index("[CLS]"   )
								_UpperCamelCase											=   sep_token_id or vocab_list.index("[SEP]"   )
								_UpperCamelCase											=   pad_token_id or vocab_list.index("[PAD]"   )
								_UpperCamelCase											=   ShrinkLongestTrimmer(max_length - 3			,     axis=1   )  # Allow room for special tokens
								_UpperCamelCase											=   max_length
								_UpperCamelCase											=   padding
								_UpperCamelCase											=   truncation
								_UpperCamelCase											=   pad_to_multiple_of
								_UpperCamelCase											=   return_token_type_ids
								_UpperCamelCase											=   return_attention_mask




			@classmethod
			def       a	(					cls			,     A_			,     **A_   ):  # noqa: F821
								_UpperCamelCase											=   kwargs.pop("do_lower_case"			,     A_   )
								_UpperCamelCase											=   tokenizer.do_lower_case if do_lower_case is None else do_lower_case
								_UpperCamelCase											=   kwargs.pop("cls_token_id"			,     A_   )
								_UpperCamelCase											=   tokenizer.cls_token_id if cls_token_id is None else cls_token_id
								_UpperCamelCase											=   kwargs.pop("sep_token_id"			,     A_   )
								_UpperCamelCase											=   tokenizer.sep_token_id if sep_token_id is None else sep_token_id
								_UpperCamelCase											=   kwargs.pop("pad_token_id"			,     A_   )
								_UpperCamelCase											=   tokenizer.pad_token_id if pad_token_id is None else pad_token_id

								_UpperCamelCase											=   tokenizer.get_vocab()
								_UpperCamelCase											=   sorted([(wordpiece, idx) for wordpiece, idx in vocab.items()]			,     key=lambda A_   : x[1]   )
								_UpperCamelCase											=   [entry[0] for entry in vocab]
								return cls(
								    vocab_list=A_			,     do_lower_case=A_			,     cls_token_id=A_			,     sep_token_id=A_			,     pad_token_id=A_			,     **A_			,     )




			@classmethod
			def       a	(					cls			,     A_			,     *A_			,     **A_   ):
								try:
													_UpperCamelCase											=   BertTokenizer.from_pretrained(A_			,     *A_			,     **A_   )
								except:  # noqa: E722
													from .tokenization_bert_fast import BertTokenizerFast

													_UpperCamelCase											=   BertTokenizerFast.from_pretrained(A_			,     *A_			,     **A_   )
								return cls.from_tokenizer(A_			,     **A_   )




			def       a	(					self			,     A_   ):
								if self.do_lower_case:
													_UpperCamelCase											=   case_fold_utfa(A_   )
								_UpperCamelCase											=   self.tf_tokenizer.tokenize(A_   )
								return tokens.merge_dims(1			,     -1   )




			def       a	(					self			,     A_			,     A_=None			,     A_=None			,     A_=None			,     A_=None			,     A_=None			,     A_=None			,     A_=None			,     ):
								if padding is None:
													_UpperCamelCase											=   self.padding
								if padding not in ("longest", "max_length"):
													raise ValueError("Padding must be either 'longest' or 'max_length'!"   )
								if max_length is not None and text_pair is not None:
													# Because we have to instantiate a Trimmer to do it properly
													raise ValueError("max_length cannot be overridden at call time when truncating paired texts!"   )
								if max_length is None:
													_UpperCamelCase											=   self.max_length
								if truncation is None:
													_UpperCamelCase											=   self.truncation
								if pad_to_multiple_of is None:
													_UpperCamelCase											=   self.pad_to_multiple_of
								if return_token_type_ids is None:
													_UpperCamelCase											=   self.return_token_type_ids
								if return_attention_mask is None:
													_UpperCamelCase											=   self.return_attention_mask
								if not isinstance(A_			,     tf.Tensor   ):
													_UpperCamelCase											=   tf.convert_to_tensor(A_   )
								if text_pair is not None and not isinstance(A_			,     tf.Tensor   ):
													_UpperCamelCase											=   tf.convert_to_tensor(A_   )
								if text_pair is not None:
													if text.shape.rank > 1:
																		raise ValueError("text argument should not be multidimensional when a text pair is supplied!"   )
													if text_pair.shape.rank > 1:
																		raise ValueError("text_pair should not be multidimensional!"   )
								if text.shape.rank == 2:
													_UpperCamelCase				,	_UpperCamelCase											=   text[:, 0], text[:, 1]
								_UpperCamelCase											=   self.unpaired_tokenize(A_   )
								if text_pair is None:  # Unpaired text
													if truncation:
																		_UpperCamelCase											=   text[:, : max_length - 2]  # Allow room for special tokens
													_UpperCamelCase				,	_UpperCamelCase											=   combine_segments(
													    (text,)			,     start_of_sequence_id=self.cls_token_id			,     end_of_segment_id=self.sep_token_id   )
								else:  # Paired text
													_UpperCamelCase											=   self.unpaired_tokenize(A_   )
													if truncation:
																		_UpperCamelCase				,	_UpperCamelCase											=   self.paired_trimmer.trim([text, text_pair]   )
													_UpperCamelCase				,	_UpperCamelCase											=   combine_segments(
													    (text, text_pair)			,     start_of_sequence_id=self.cls_token_id			,     end_of_segment_id=self.sep_token_id   )
								if padding == "longest":
													_UpperCamelCase											=   input_ids.bounding_shape(axis=1   )
													if pad_to_multiple_of is not None:
																		# No ceiling division in tensorflow, so we negate floordiv instead
																		_UpperCamelCase											=   pad_to_multiple_of * (-tf.math.floordiv(-pad_length			,     A_   ))
								else:
													_UpperCamelCase											=   max_length

								_UpperCamelCase				,	_UpperCamelCase											=   pad_model_inputs(A_			,     max_seq_length=A_			,     pad_value=self.pad_token_id   )
								_UpperCamelCase											=   {"input_ids": input_ids}
								if return_attention_mask:
													_UpperCamelCase											=   attention_mask
								if return_token_type_ids:
													_UpperCamelCase				,	_UpperCamelCase											=   pad_model_inputs(
													    A_			,     max_seq_length=A_			,     pad_value=self.pad_token_id   )
													_UpperCamelCase											=   token_type_ids
								return output




			def       a	(					self   ):
								return {
								    "vocab_list": self.vocab_list,
								    "do_lower_case": self.do_lower_case,
								    "cls_token_id": self.cls_token_id,
								    "sep_token_id": self.sep_token_id,
								    "pad_token_id": self.pad_token_id,
								}



