"""simple docstring"""





import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin
@require_tokenizers
class  _snake_case     (					a__				, unittest.TestCase		):
						snake_case__			  =			LEDTokenizer
						snake_case__			  =			LEDTokenizerFast
						snake_case__			  =			True






						def       lowerCamelCase__     (       self      :			Dict    ):
													super().setUp()
													__lowerCamelCase					:		Optional[Any]		   =     [
													    "l",
													    "o",
													    "w",
													    "e",
													    "r",
													    "s",
													    "t",
													    "i",
													    "d",
													    "n",
													    "\u0120",
													    "\u0120l",
													    "\u0120n",
													    "\u0120lo",
													    "\u0120low",
													    "er",
													    "\u0120lowest",
													    "\u0120newer",
													    "\u0120wider",
													    "<unk>",
													]
													__lowerCamelCase					:		List[Any]		   =     dict(zip(UpperCAmelCase							,					range(len(UpperCAmelCase    )    )    )    )
													__lowerCamelCase					:		List[Any]		   =     ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
													__lowerCamelCase					:		List[str]		   =     {"unk_token": "<unk>"}

													__lowerCamelCase					:		List[str]		   =     os.path.join(self.tmpdirname							,					VOCAB_FILES_NAMES["vocab_file"]    )
													__lowerCamelCase					:		str		   =     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(UpperCAmelCase    ) + "\n"    )
													with open(self.merges_file							,					"w"							,					encoding="utf-8"    ) as fp:
																				fp.write("\n".join(UpperCAmelCase    )    )






						def       lowerCamelCase__     (       self      :			str							,					**UpperCAmelCase      :			Any    ):
													kwargs.update(self.special_tokens_map    )
													return self.tokenizer_class.from_pretrained(self.tmpdirname							,					**UpperCAmelCase    )






						def       lowerCamelCase__     (       self      :			str							,					**UpperCAmelCase      :			Optional[Any]    ):
													kwargs.update(self.special_tokens_map    )
													return self.rust_tokenizer_class.from_pretrained(self.tmpdirname							,					**UpperCAmelCase    )






						def       lowerCamelCase__     (       self      :			Union[str, Any]							,					UpperCAmelCase      :			Optional[Any]    ):
													return "lower newer", "lower newer"






						@cached_property
						def       lowerCamelCase__     (       self      :			int    ):
													return LEDTokenizer.from_pretrained("allenai/led-base-16384"    )






						@cached_property
						def       lowerCamelCase__     (       self      :			Dict    ):
													return LEDTokenizerFast.from_pretrained("allenai/led-base-16384"    )






						@require_torch
						def       lowerCamelCase__     (       self      :			Tuple    ):
													__lowerCamelCase					:		Union[str, Any]		   =     ["A long paragraph for summarization.", "Another paragraph for summarization."]
													__lowerCamelCase					:		Dict		   =     [0, 250, 251, 17818, 13, 39186, 1938, 4, 2]

													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		Dict		   =     tokenizer(UpperCAmelCase							,					max_length=len(UpperCAmelCase    )							,					padding=UpperCAmelCase							,					return_tensors="pt"    )
																				self.assertIsInstance(UpperCAmelCase							,					UpperCAmelCase    )

																				self.assertEqual((2, 9)							,					batch.input_ids.shape    )
																				self.assertEqual((2, 9)							,					batch.attention_mask.shape    )
																				__lowerCamelCase					:		str		   =     batch.input_ids.tolist()[0]
																				self.assertListEqual(UpperCAmelCase							,					UpperCAmelCase    )






						@require_torch
						def       lowerCamelCase__     (       self      :			Dict    ):
													__lowerCamelCase					:		Any		   =     ["A long paragraph for summarization.", "Another paragraph for summarization."]
													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		Dict		   =     tokenizer(UpperCAmelCase							,					padding=UpperCAmelCase							,					return_tensors="pt"    )
																				self.assertIn("input_ids"							,					UpperCAmelCase    )
																				self.assertIn("attention_mask"							,					UpperCAmelCase    )
																				self.assertNotIn("labels"							,					UpperCAmelCase    )
																				self.assertNotIn("decoder_attention_mask"							,					UpperCAmelCase    )






						@require_torch
						def       lowerCamelCase__     (       self      :			List[str]    ):
													__lowerCamelCase					:		Tuple		   =     [
													    "Summary of the text.",
													    "Another summary.",
													]
													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		str		   =     tokenizer(text_target=UpperCAmelCase							,					max_length=32							,					padding="max_length"							,					return_tensors="pt"    )
																				self.assertEqual(32							,					targets["input_ids"].shape[1]    )






						@require_torch
						def       lowerCamelCase__     (       self      :			List[Any]    ):
													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		Any		   =     tokenizer(
																				    ["I am a small frog" * 1024, "I am a small frog"]							,					padding=UpperCAmelCase							,					truncation=UpperCAmelCase							,					return_tensors="pt"    )
																				self.assertIsInstance(UpperCAmelCase							,					UpperCAmelCase    )
																				self.assertEqual(batch.input_ids.shape							,					(2, 5122)    )






						@require_torch
						def       lowerCamelCase__     (       self      :			str    ):
													__lowerCamelCase					:		Union[str, Any]		   =     ["A long paragraph for summarization."]
													__lowerCamelCase					:		Optional[Any]		   =     [
													    "Summary of the text.",
													]
													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		Union[str, Any]		   =     tokenizer(UpperCAmelCase							,					return_tensors="pt"    )
																				__lowerCamelCase					:		Optional[int]		   =     tokenizer(text_target=UpperCAmelCase							,					return_tensors="pt"    )
																				__lowerCamelCase					:		str		   =     inputs["input_ids"]
																				__lowerCamelCase					:		Tuple		   =     targets["input_ids"]
																				self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item()    )
																				self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item()    )
																				self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item()    )
																				self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item()    )






						@require_torch
						def       lowerCamelCase__     (       self      :			Any    ):
													for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
																				__lowerCamelCase					:		str		   =     ["Summary of the text.", "Another summary."]
																				__lowerCamelCase					:		str		   =     [[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

																				__lowerCamelCase					:		Dict		   =     tokenizer(UpperCAmelCase							,					padding=UpperCAmelCase    )
																				__lowerCamelCase					:		List[Any]		   =     [[0] * len(UpperCAmelCase    ) for x in encoded_output["input_ids"]]
																				__lowerCamelCase					:		List[str]		   =     tokenizer.pad(UpperCAmelCase    )
																				self.assertSequenceEqual(outputs["global_attention_mask"]							,					UpperCAmelCase    )






						def       lowerCamelCase__     (       self      :			Union[str, Any]    ):
													pass







						def       lowerCamelCase__     (       self      :			Optional[int]    ):
													for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
																				with self.subTest(F"""{tokenizer.__class__.__name__} ({pretrained_name})"""    ):
																											__lowerCamelCase					:		Union[str, Any]		   =     self.rust_tokenizer_class.from_pretrained(UpperCAmelCase							,					**UpperCAmelCase    )
																											__lowerCamelCase					:		List[str]		   =     self.tokenizer_class.from_pretrained(UpperCAmelCase							,					**UpperCAmelCase    )
																											__lowerCamelCase					:		List[str]		   =     "A, <mask> AllenNLP sentence."
																											__lowerCamelCase					:		Optional[int]		   =     tokenizer_r.encode_plus(UpperCAmelCase							,					add_special_tokens=UpperCAmelCase							,					return_token_type_ids=UpperCAmelCase    )
																											__lowerCamelCase					:		Optional[Any]		   =     tokenizer_p.encode_plus(UpperCAmelCase							,					add_special_tokens=UpperCAmelCase							,					return_token_type_ids=UpperCAmelCase    )
																											self.assertEqual(sum(tokens_r["token_type_ids"]    )							,					sum(tokens_p["token_type_ids"]    )    )
																											self.assertEqual(
																											    sum(tokens_r["attention_mask"]    ) / len(tokens_r["attention_mask"]    )							,					sum(tokens_p["attention_mask"]    ) / len(tokens_p["attention_mask"]    )							,					)

																											__lowerCamelCase					:		Any		   =     tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]    )
																											__lowerCamelCase					:		Any		   =     tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]    )
																											self.assertSequenceEqual(tokens_p["input_ids"]							,					[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]    )
																											self.assertSequenceEqual(tokens_r["input_ids"]							,					[0, 250, 6, 50264, 3823, 487, 21992, 3645, 4, 2]    )

																											self.assertSequenceEqual(
																											    UpperCAmelCase							,					["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )
																											self.assertSequenceEqual(
																											    UpperCAmelCase							,					["<s>", "A", ",", "<mask>", "ĠAllen", "N", "LP", "Ġsentence", ".", "</s>"]    )
"""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  =				'''CompVis/stable-diffusion-v1-1'''
__A  =				'''CompVis/stable-diffusion-v1-2'''
__A  =				'''CompVis/stable-diffusion-v1-3'''
__A  =				'''CompVis/stable-diffusion-v1-4'''
class  _snake_case     (					a__		):






						def __init__(       self      :			int							,					UpperCAmelCase      :			AutoencoderKL							,					UpperCAmelCase      :			CLIPTextModel							,					UpperCAmelCase      :			CLIPTokenizer							,					UpperCAmelCase      :			UNetaDConditionModel							,					UpperCAmelCase      :			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]							,					UpperCAmelCase      :			StableDiffusionSafetyChecker							,					UpperCAmelCase      :			CLIPImageProcessor							,					UpperCAmelCase      :			bool = True							,					):
													super()._init_()

													__lowerCamelCase					:		Optional[int]		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		Optional[int]		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		Tuple		   =     StableDiffusionPipeline.from_pretrained(UpperCAmelCase    )
													__lowerCamelCase					:		List[str]		   =     StableDiffusionPipeline(
													    vae=UpperCAmelCase							,					text_encoder=UpperCAmelCase							,					tokenizer=UpperCAmelCase							,					unet=UpperCAmelCase							,					scheduler=UpperCAmelCase							,					safety_checker=UpperCAmelCase							,					feature_extractor=UpperCAmelCase							,					requires_safety_checker=UpperCAmelCase							,					)

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






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






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






						def       lowerCamelCase__     (       self      :			Tuple    ):
													self.enable_attention_slicing(UpperCAmelCase    )






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Optional[Any]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Dict							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Union[str, Any]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Tuple							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Dict							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)






						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			Optional[Any]							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			List[str]							,					):
													return self.pipea(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)







						@torch.no_grad()
						def       lowerCamelCase__     (       self      :			str							,					UpperCAmelCase      :			Union[str, List[str]]							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 512							,					UpperCAmelCase      :			int = 50							,					UpperCAmelCase      :			float = 7.5							,					UpperCAmelCase      :			Optional[Union[str, List[str]]] = None							,					UpperCAmelCase      :			Optional[int] = 1							,					UpperCAmelCase      :			float = 0.0							,					UpperCAmelCase      :			Optional[torch.Generator] = None							,					UpperCAmelCase      :			Optional[torch.FloatTensor] = None							,					UpperCAmelCase      :			Optional[str] = "pil"							,					UpperCAmelCase      :			bool = True							,					UpperCAmelCase      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None							,					UpperCAmelCase      :			int = 1							,					**UpperCAmelCase      :			Tuple							,					):
													__lowerCamelCase					:		Optional[int]		   =     "cuda" if torch.cuda.is_available() else "cpu"
													self.to(UpperCAmelCase    )

													# 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					:		str		   =     self.textaimg_sda_a(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)

													# Get first result from Stable Diffusion Checkpoint v1.2
													__lowerCamelCase					:		Optional[int]		   =     self.textaimg_sda_a(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)

													# Get first result from Stable Diffusion Checkpoint v1.3
													__lowerCamelCase					:		Any		   =     self.textaimg_sda_a(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)

													# Get first result from Stable Diffusion Checkpoint v1.4
													__lowerCamelCase					:		Optional[Any]		   =     self.textaimg_sda_a(
													    prompt=UpperCAmelCase							,					height=UpperCAmelCase							,					width=UpperCAmelCase							,					num_inference_steps=UpperCAmelCase							,					guidance_scale=UpperCAmelCase							,					negative_prompt=UpperCAmelCase							,					num_images_per_prompt=UpperCAmelCase							,					eta=UpperCAmelCase							,					generator=UpperCAmelCase							,					latents=UpperCAmelCase							,					output_type=UpperCAmelCase							,					return_dict=UpperCAmelCase							,					callback=UpperCAmelCase							,					callback_steps=UpperCAmelCase							,					**UpperCAmelCase							,					)

													# 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]]    )