
import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
					from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
					from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING


def 		UpperCAmelCase     (      a_		)						->      str:







				"""simple docstring"""



				return 1.0 / (1.0 + np.exp(-_outputs		))


def 		UpperCAmelCase     (      a_		)						->      Optional[Any]:







				"""simple docstring"""



				__A       =					np.max(_outputs						,  axis=-1						,  keepdims=a_		)
				__A       =					np.exp(_outputs - maxes		)
				return shifted_exp / shifted_exp.sum(axis=-1						,  keepdims=a_		)





class 				UpperCAmelCase (    __SCREAMING_SNAKE_CASE    ):




	'''simple docstring'''





	snake_case_          =	"sigmoid"
	snake_case_          =	"softmax"
	snake_case_          =	"none"





@add_end_docstrings(
    __SCREAMING_SNAKE_CASE     ,     R"\n        return_all_scores (`bool`, *optional*, defaults to `False`):\n            Whether to return all prediction scores or just the one of the predicted class.\n        function_to_apply (`str`, *optional*, defaults to `\"default\"`):\n            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:\n\n            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model\n              has several labels, will apply the softmax function on the output.\n            - `\"sigmoid\"`: Applies the sigmoid function on the output.\n            - `\"softmax\"`: Applies the softmax function on the output.\n            - `\"none\"`: Does not apply any function on the output.\n    "     ,     )
class 				UpperCAmelCase (    __SCREAMING_SNAKE_CASE    ):




	'''simple docstring'''





	snake_case_          =	False
	snake_case_          =	ClassificationFunction.NONE






	def __init__(			self   :					Dict				,**A   :					Optional[int]					):
					super().__init__(**A					)

					self.check_model_type(
					    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
					    if self.framework == "tf"
					    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING					)






	def 							UpperCamelCase_    (			self   :					Any				,A   :					Optional[int]=None				,A   :					str=None				,A   :					Dict=""				,**A   :					str					):
					# Using "" as default argument because we're going to use `top_k=None` in user code to declare
					# "No top_k"
					__A       =					tokenizer_kwargs

					__A       =					{}
					if hasattr(self.model.config				,"return_all_scores"					) and return_all_scores is None:
									__A       =					self.model.config.return_all_scores

					if isinstance(A				,A					) or top_k is None:
									__A       =					top_k
									__A       =					False
					elif return_all_scores is not None:
									warnings.warn(
									    "`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"
									    " `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."				,A				,)
									if return_all_scores:
													__A       =					None
									else:
													__A       =					1

					if isinstance(A				,A					):
									__A       =					ClassificationFunction[function_to_apply.upper()]

					if function_to_apply is not None:
									__A       =					function_to_apply
					return preprocess_params, {}, postprocess_params






	def __call__(			self   :					List[str]				,*A   :					Optional[Any]				,**A   :					Tuple					):
					__A       =					super().__call__(*A				,**A					)
					# TODO try and retrieve it in a nicer way from _sanitize_parameters.
					__A       =					"top_k" not in kwargs
					if isinstance(args[0]				,A					) and _legacy:
									# This pipeline is odd, and return a list when single item is run
									return [result]
					else:
									return result






	def 							UpperCamelCase_    (			self   :					Tuple				,A   :					Any				,**A   :					List[str]					):
					__A       =					self.framework
					if isinstance(A				,A					):
									return self.tokenizer(**A				,return_tensors=A				,**A					)
					elif isinstance(A				,A					) and len(A					) == 1 and isinstance(inputs[0]				,A					) and len(inputs[0]					) == 2:
									# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
									return self.tokenizer(
									    text=inputs[0][0]				,text_pair=inputs[0][1]				,return_tensors=A				,**A					)
					elif isinstance(A				,A					):
									# This is likely an invalid usage of the pipeline attempting to pass text pairs.
									raise ValueError(
									    "The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"
									    " dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair."					)
					return self.tokenizer(A				,return_tensors=A				,**A					)






	def 							UpperCamelCase_    (			self   :					List[Any]				,A   :					str					):
					return self.model(**A					)







	def 							UpperCamelCase_    (			self   :					Optional[Any]				,A   :					Any				,A   :					Tuple=None				,A   :					List[Any]=1				,A   :					List[str]=True					):
					# `_legacy` is used to determine if we're running the naked pipeline and in backward
					# compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running
					# the more natural result containing the list.
					# Default value before `set_parameters`
					if function_to_apply is None:
									if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
													__A       =					ClassificationFunction.SIGMOID
									elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
													__A       =					ClassificationFunction.SOFTMAX
									elif hasattr(self.model.config				,"function_to_apply"					) and function_to_apply is None:
													__A       =					self.model.config.function_to_apply
									else:
													__A       =					ClassificationFunction.NONE

					__A       =					model_outputs["logits"][0]
					__A       =					outputs.numpy()

					if function_to_apply == ClassificationFunction.SIGMOID:
									__A       =					sigmoid(A					)
					elif function_to_apply == ClassificationFunction.SOFTMAX:
									__A       =					softmax(A					)
					elif function_to_apply == ClassificationFunction.NONE:
									__A       =					outputs
					else:
									raise ValueError(f'''Unrecognized `function_to_apply` argument: {function_to_apply}'''					)

					if top_k == 1 and _legacy:
									return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

					__A       =					[
					    {"label": self.model.config.idalabel[i], "score": score.item()} for i, score in enumerate(A					)
					]
					if not _legacy:
									dict_scores.sort(key=lambda A					: x["score"]				,reverse=A					)
									if top_k is not None:
													__A       =					dict_scores[:top_k]
					return dict_scores




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


_lowercase							:   Optional[int]						=						False






@skip_mps
class    _UpperCamelCase     (       __snake_case     ,		__snake_case     ,		__snake_case     ,		unittest.TestCase					):

				"""simple docstring"""







				lowerCAmelCase					=			StableDiffusionAttendAndExcitePipeline
				lowerCAmelCase					=			False
				lowerCAmelCase					=			TEXT_TO_IMAGE_PARAMS
				lowerCAmelCase					=			TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'}					)
				lowerCAmelCase					=			TEXT_TO_IMAGE_IMAGE_PARAMS
				lowerCAmelCase					=			TEXT_TO_IMAGE_IMAGE_PARAMS

				@classmethod
				def   _UpperCAmelCase       (    cls )						->					List[Any]:
					super().setUpClass()
					torch.use_deterministic_algorithms(a__ )

				@classmethod
				def   _UpperCAmelCase       (    cls )						->					Tuple:
					super().tearDownClass()
					torch.use_deterministic_algorithms(a__ )

				def   _UpperCAmelCase       (    self )						->					Dict:
					torch.manual_seed(0 )
					A             =					UNetaDConditionModel(
					    block_out_channels=(32, 64)					, layers_per_block=1					, sample_size=32					, in_channels=4					, out_channels=4					, down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""")					, up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""")					, cross_attention_dim=32					, attention_head_dim=(2, 4)					, use_linear_projection=a__					, )
					A             =					DDIMScheduler(
					    beta_start=0.0_00_85					, beta_end=0.0_12					, beta_schedule="""scaled_linear"""					, clip_sample=a__					, set_alpha_to_one=a__					, )
					torch.manual_seed(0 )
					A             =					AutoencoderKL(
					    block_out_channels=[32, 64]					, in_channels=3					, out_channels=3					, down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""]					, up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""]					, latent_channels=4					, sample_size=128					, )
					torch.manual_seed(0 )
					A             =					CLIPTextConfig(
					    bos_token_id=0					, eos_token_id=2					, hidden_size=32					, intermediate_size=37					, layer_norm_eps=1e-05					, num_attention_heads=4					, num_hidden_layers=5					, pad_token_id=1					, vocab_size=1000					, hidden_act="""gelu"""					, projection_dim=512					, )
					A             =					CLIPTextModel(a__ )
					A             =					CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )

					A             =					{
					    """unet""": unet,
					    """scheduler""": scheduler,
					    """vae""": vae,
					    """text_encoder""": text_encoder,
					    """tokenizer""": tokenizer,
					    """safety_checker""": None,
					    """feature_extractor""": None,
					}

					return components

				def   _UpperCAmelCase       (    self					, a__					, a__=0 )						->					Optional[Any]:
					if str(a__ ).startswith("""mps""" ):
						A             =					torch.manual_seed(a__ )
					else:
						A             =					torch.Generator(device=a__ ).manual_seed(a__ )
					A             =					A             =					{
					    """prompt""": """a cat and a frog""",
					    """token_indices""": [2, 5],
					    """generator""": generator,
					    """num_inference_steps""": 1,
					    """guidance_scale""": 6.0,
					    """output_type""": """numpy""",
					    """max_iter_to_alter""": 2,
					    """thresholds""": {0: 0.7},
					}
					return inputs

				def   _UpperCAmelCase       (    self )						->					Union[str, Any]:
					A             =					"""cpu"""

					A             =					self.get_dummy_components()
					A             =					self.pipeline_class(**a__ )
					pipe.to(a__ )
					pipe.set_progress_bar_config(disable=a__ )

					A             =					self.get_dummy_inputs(a__ )
					A             =					pipe(**a__ ).images
					A             =					image[0, -3:, -3:, -1]

					self.assertEqual(image.shape					, (1, 64, 64, 3) )
					A             =					np.array(
					    [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96] )
					A             =					np.abs(image_slice.flatten() - expected_slice ).max()
					self.assertLessEqual(a__					, 1e-3 )

				def   _UpperCAmelCase       (    self )						->					List[Any]:
					super().test_cpu_offload_forward_pass(expected_max_diff=5e-4 )

				def   _UpperCAmelCase       (    self )						->					Dict:
					# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
					self._test_inference_batch_consistent(batch_sizes=[1, 2] )

				def   _UpperCAmelCase       (    self )						->					Any:
					self._test_inference_batch_single_identical(batch_size=2					, expected_max_diff=7e-4 )

				def   _UpperCAmelCase       (    self )						->					Optional[Any]:
					super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3 )

				def   _UpperCAmelCase       (    self )						->					str:
					super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5e-4 )

				def   _UpperCAmelCase       (    self )						->					int:
					super().test_save_load_local(expected_max_difference=5e-4 )

				def   _UpperCAmelCase       (    self )						->					Optional[Any]:
					super().test_save_load_optional_components(expected_max_difference=4e-4 )






@require_torch_gpu
@slow
class    _UpperCamelCase     (       unittest.TestCase					):

				"""simple docstring"""







				@classmethod
				def   _UpperCAmelCase       (    cls )						->					Tuple:
					super().setUpClass()
					torch.use_deterministic_algorithms(a__ )

				@classmethod
				def   _UpperCAmelCase       (    cls )						->					Dict:
					super().tearDownClass()
					torch.use_deterministic_algorithms(a__ )

				def   _UpperCAmelCase       (    self )						->					Optional[Any]:
					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()

				def   _UpperCAmelCase       (    self )						->					int:
					A             =					torch.manual_seed(51 )

					A             =					StableDiffusionAttendAndExcitePipeline.from_pretrained(
					    """CompVis/stable-diffusion-v1-4"""					, safety_checker=a__					, torch_dtype=torch.floataa )
					pipe.to("""cuda""" )

					A             =					"""a painting of an elephant with glasses"""
					A             =					[5, 7]

					A             =					pipe(
					    prompt=a__					, token_indices=a__					, guidance_scale=7.5					, generator=a__					, num_inference_steps=5					, max_iter_to_alter=5					, output_type="""numpy"""					, ).images[0]

					A             =					load_numpy(
					    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy""" )
					assert np.abs((expected_image - image).max() ) < 5e-1



