


'''simple docstring'''



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

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


A__		:					Dict												=  '''CompVis/stable-diffusion-v1-1'''
A__		:					int												=  '''CompVis/stable-diffusion-v1-2'''
A__		:					List[Any]												=  '''CompVis/stable-diffusion-v1-3'''
A__		:					List[Any]												=  '''CompVis/stable-diffusion-v1-4'''





class    UpperCAmelCase_  (UpperCamelCase_  ):





    """simple docstring"""






    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[Any]:
         super()._init_()

         __lowerCamelCase   :	Dict								=		StableDiffusionPipeline.from_pretrained(A_	)
         __lowerCamelCase   :	Union[str, Any]								=		StableDiffusionPipeline.from_pretrained(A_	)
         __lowerCamelCase   :	List[str]								=		StableDiffusionPipeline.from_pretrained(A_	)
         __lowerCamelCase   :	Union[str, Any]								=		StableDiffusionPipeline(
             vae=A_			,     text_encoder=A_			,     tokenizer=A_			,     unet=A_			,     scheduler=A_			,     safety_checker=A_			,     feature_extractor=A_			,     requires_safety_checker=A_			,     )

         self.register_modules(pipelinea=self.pipea			,     pipelinea=self.pipea			,     pipelinea=self.pipea			,     pipelinea=self.pipea	)







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







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







    def       lowercase_				(							self	)				->     Union[str, Any]:
         self.enable_attention_slicing(A_	)







    @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			,     **SCREAMING_SNAKE_CASE_			,     )				->     Optional[Any]:
         return self.pipea(
             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_			,     **A_			,     )







    @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			,     **SCREAMING_SNAKE_CASE_			,     )				->     List[Any]:
         return self.pipea(
             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_			,     **A_			,     )







    @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			,     **SCREAMING_SNAKE_CASE_			,     )				->     Tuple:
         return self.pipea(
             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_			,     **A_			,     )







    @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			,     **SCREAMING_SNAKE_CASE_			,     )				->     Dict:
         return self.pipea(
             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_			,     **A_			,     )







    @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			,     **SCREAMING_SNAKE_CASE_			,     )				->     int:
         __lowerCamelCase   :	List[Any]								=		'''cuda''' if torch.cuda.is_available() else '''cpu'''
         self.to(A_	)

         # Checks if the height and width are divisible by 8 or not
         if height % 8 != 0 or width % 8 != 0:
              raise ValueError(f'`height` and `width` must be divisible by 8 but are {height} and {width}.'	)

         # Get first result from Stable Diffusion Checkpoint v1.1
         __lowerCamelCase   :	Optional[Any]								=		self.textaimg_sda_a(
             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_			,     **A_			,     )

         # Get first result from Stable Diffusion Checkpoint v1.2
         __lowerCamelCase   :	str								=		self.textaimg_sda_a(
             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_			,     **A_			,     )

         # Get first result from Stable Diffusion Checkpoint v1.3
         __lowerCamelCase   :	List[str]								=		self.textaimg_sda_a(
             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_			,     **A_			,     )

         # Get first result from Stable Diffusion Checkpoint v1.4
         __lowerCamelCase   :	List[Any]								=		self.textaimg_sda_a(
             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_			,     **A_			,     )

         # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
         return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]	)











import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_base import BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import PaddingStrategy, logging
from .tokenization_realm import RealmTokenizer


A__  :  str								=					logging.get_logger(__name__)

A__  :  Any								=					{'''vocab_file''': '''vocab.txt''', '''tokenizer_file''': '''tokenizer.json'''}

A__  :  str								=					{
    '''vocab_file''': {
        '''google/realm-cc-news-pretrained-embedder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-encoder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-scorer''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/vocab.txt'''
        ),
        '''google/realm-cc-news-pretrained-openqa''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/vocab.txt'''
        ),
        '''google/realm-orqa-nq-openqa''': '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/vocab.txt''',
        '''google/realm-orqa-nq-reader''': '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/vocab.txt''',
        '''google/realm-orqa-wq-openqa''': '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/vocab.txt''',
        '''google/realm-orqa-wq-reader''': '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/vocab.txt''',
    },
    '''tokenizer_file''': {
        '''google/realm-cc-news-pretrained-embedder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-embedder/resolve/main/tokenizer.jsont'''
        ),
        '''google/realm-cc-news-pretrained-encoder''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-encoder/resolve/main/tokenizer.json'''
        ),
        '''google/realm-cc-news-pretrained-scorer''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-scorer/resolve/main/tokenizer.json'''
        ),
        '''google/realm-cc-news-pretrained-openqa''': (
            '''https://huggingface.co/google/realm-cc-news-pretrained-openqa/aresolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-nq-openqa''': (
            '''https://huggingface.co/google/realm-orqa-nq-openqa/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-nq-reader''': (
            '''https://huggingface.co/google/realm-orqa-nq-reader/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-wq-openqa''': (
            '''https://huggingface.co/google/realm-orqa-wq-openqa/resolve/main/tokenizer.json'''
        ),
        '''google/realm-orqa-wq-reader''': (
            '''https://huggingface.co/google/realm-orqa-wq-reader/resolve/main/tokenizer.json'''
        ),
    },
}

A__  :  Union[str, Any]								=					{
    '''google/realm-cc-news-pretrained-embedder''': 512,
    '''google/realm-cc-news-pretrained-encoder''': 512,
    '''google/realm-cc-news-pretrained-scorer''': 512,
    '''google/realm-cc-news-pretrained-openqa''': 512,
    '''google/realm-orqa-nq-openqa''': 512,
    '''google/realm-orqa-nq-reader''': 512,
    '''google/realm-orqa-wq-openqa''': 512,
    '''google/realm-orqa-wq-reader''': 512,
}

A__  :  Dict								=					{
    '''google/realm-cc-news-pretrained-embedder''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-encoder''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-scorer''': {'''do_lower_case''': True},
    '''google/realm-cc-news-pretrained-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-nq-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-nq-reader''': {'''do_lower_case''': True},
    '''google/realm-orqa-wq-openqa''': {'''do_lower_case''': True},
    '''google/realm-orqa-wq-reader''': {'''do_lower_case''': True},
}



class 				__snake_case						(     UpperCamelCase_						):
							_a			      = VOCAB_FILES_NAMES
							_a			      = PRETRAINED_VOCAB_FILES_MAP
							_a			      = PRETRAINED_INIT_CONFIGURATION
							_a			      = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
							_a			      = RealmTokenizer




							def __init__(       self     :       int				,				A_     :       Optional[int]=None				,				A_     :       Optional[Any]=None				,				A_     :       Optional[Any]=True				,				A_     :       Optional[int]="[UNK]"				,				A_     :       List[Any]="[SEP]"				,				A_     :       List[Any]="[PAD]"				,				A_     :       Optional[Any]="[CLS]"				,				A_     :       Dict="[MASK]"				,				A_     :       List[Any]=True				,				A_     :       List[str]=None				,				**A_     :       List[str]				,				):
									super().__init__(
									    A_				,				tokenizer_file=A_				,				do_lower_case=A_				,				unk_token=A_				,				sep_token=A_				,				pad_token=A_				,				cls_token=A_				,				mask_token=A_				,				tokenize_chinese_chars=A_				,				strip_accents=A_				,				**A_				,				)

									lowerCAmelCase_			:     Optional[int]									= json.loads(self.backend_tokenizer.normalizer.__getstate__())
									if (
									    normalizer_state.get('''lowercase'''				,				A_) != do_lower_case
									    or normalizer_state.get('''strip_accents'''				,				A_) != strip_accents
									    or normalizer_state.get('''handle_chinese_chars'''				,				A_) != tokenize_chinese_chars
									):
											lowerCAmelCase_			:     int									= getattr(A_				,				normalizer_state.pop('''type'''))
											lowerCAmelCase_			:     str									= do_lower_case
											lowerCAmelCase_			:     Dict									= strip_accents
											lowerCAmelCase_			:     Optional[Any]									= tokenize_chinese_chars
											lowerCAmelCase_			:     Union[str, Any]									= normalizer_class(**A_)

									lowerCAmelCase_			:     Any									= do_lower_case




							def    UpperCAmelCase__			(       self     :       Optional[Any]				,				A_     :       Optional[Any]				,				**A_     :       Tuple):
									lowerCAmelCase_			:     List[str]									= PaddingStrategy.MAX_LENGTH

									lowerCAmelCase_			:     str									= text
									lowerCAmelCase_			:     int									= kwargs.pop('''text_pair'''				,				A_)
									lowerCAmelCase_			:     str									= kwargs.pop('''return_tensors'''				,				A_)

									lowerCAmelCase_			:     int									= {
									    '''input_ids''': [],
									    '''attention_mask''': [],
									    '''token_type_ids''': [],
									}

									for idx, candidate_text in enumerate(A_):
											if batch_text_pair is not None:
													lowerCAmelCase_			:     List[Any]									= batch_text_pair[idx]
											else:
													lowerCAmelCase_			:     List[Any]									= None

											lowerCAmelCase_			:     int									= super().__call__(A_				,				A_				,				return_tensors=A_				,				**A_)

											lowerCAmelCase_			:     Optional[Any]									= encoded_candidates.get('''input_ids''')
											lowerCAmelCase_			:     List[str]									= encoded_candidates.get('''attention_mask''')
											lowerCAmelCase_			:     Optional[Any]									= encoded_candidates.get('''token_type_ids''')

											if encoded_input_ids is not None:
													output_data["input_ids"].append(A_)
											if encoded_attention_mask is not None:
													output_data["attention_mask"].append(A_)
											if encoded_token_type_ids is not None:
													output_data["token_type_ids"].append(A_)

									lowerCAmelCase_			:     List[str]									= {key: item for key, item in output_data.items() if len(A_) != 0}

									return BatchEncoding(A_				,				tensor_type=A_)




							def    UpperCAmelCase__			(       self     :       List[str]				,				A_     :       Tuple				,				A_     :       List[Any]=None):
									lowerCAmelCase_			:     Optional[Any]									= [self.cls_token_id] + token_ids_a + [self.sep_token_id]

									if token_ids_a:
											output += token_ids_a + [self.sep_token_id]

									return output




							def    UpperCAmelCase__			(       self     :       Tuple				,				A_     :       List[int]				,				A_     :       Optional[List[int]] = None):
									lowerCAmelCase_			:     Tuple									= [self.sep_token_id]
									lowerCAmelCase_			:     Union[str, Any]									= [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) * [0] + len(token_ids_a + sep) * [1]







							def    UpperCAmelCase__			(       self     :       List[str]				,				A_     :       str				,				A_     :       Optional[str] = None):
									lowerCAmelCase_			:     List[str]									= self._tokenizer.model.save(A_				,				name=A_)
									return tuple(A_)





