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 	__lowerCamelCase							(UpperCAmelCase__     :							Dict  ):
     return 1.0 / (1.0 + np.exp(-_outputs  ))





def 	__lowerCamelCase							(UpperCAmelCase__     :							Optional[Any]  ):
     SCREAMING_SNAKE_CASE    			=       np.max(_outputs      , axis=-1      , keepdims=UpperCAmelCase__  )
     SCREAMING_SNAKE_CASE    			=       np.exp(_outputs - maxes  )
     return shifted_exp / shifted_exp.sum(axis=-1      , keepdims=UpperCAmelCase__  )


class 						lowercase    (     a     ):
       lowercase__						:       List[str]								=							"""sigmoid"""
       lowercase__						:       str								=							"""softmax"""
       lowercase__						:       List[Any]								=							"""none"""



@add_end_docstrings(
    a				,       R"""
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `\"default\"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `\"sigmoid\"`: Applies the sigmoid function on the output.
            - `\"softmax\"`: Applies the softmax function on the output.
            - `\"none\"`: Does not apply any function on the output.
    """				,       )
class 						lowercase    (     a     ):
       lowercase__						:       Optional[int]								=							False
       lowercase__						:       int								=							ClassificationFunction.NONE




       def __init__(						self   :					Optional[Any]	,							**_UpperCamelCase   :					List[str]      )					->				List[str]:



            '''simple docstring'''

            super().__init__(**_UpperCamelCase      )

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




       def 	__snake_case(						self   :					int	,							_UpperCamelCase   :					List[str]=None	,							_UpperCamelCase   :					Tuple=None	,							_UpperCamelCase   :					str=""	,							**_UpperCamelCase   :					Any      )					->				List[str]:



            '''simple docstring'''

            SCREAMING_SNAKE_CASE    			=       tokenizer_kwargs

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

            if isinstance(_UpperCamelCase	,							_UpperCamelCase      ) or top_k is None:
                 SCREAMING_SNAKE_CASE    			=       top_k
                 SCREAMING_SNAKE_CASE    			=       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`."	,							_UpperCamelCase	,							)
                 if return_all_scores:
                      SCREAMING_SNAKE_CASE    			=       None
                 else:
                      SCREAMING_SNAKE_CASE    			=       1

            if isinstance(_UpperCamelCase	,							_UpperCamelCase      ):
                 SCREAMING_SNAKE_CASE    			=       ClassificationFunction[function_to_apply.upper()]

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




       def __call__(						self   :					Any	,							*_UpperCamelCase   :					List[str]	,							**_UpperCamelCase   :					List[Any]      )					->				Dict:



            '''simple docstring'''

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




       def 	__snake_case(						self   :					Optional[Any]	,							_UpperCamelCase   :					str	,							**_UpperCamelCase   :					List[Any]      )					->				Dict[str, GenericTensor]:



            '''simple docstring'''

            SCREAMING_SNAKE_CASE    			=       self.framework
            if isinstance(_UpperCamelCase	,							_UpperCamelCase      ):
                 return self.tokenizer(**_UpperCamelCase	,							return_tensors=_UpperCamelCase	,							**_UpperCamelCase      )
            elif isinstance(_UpperCamelCase	,							_UpperCamelCase      ) and len(_UpperCamelCase      ) == 1 and isinstance(inputs[0]	,							_UpperCamelCase      ) 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=_UpperCamelCase	,							**_UpperCamelCase      )
            elif isinstance(_UpperCamelCase	,							_UpperCamelCase      ):
                 # 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(_UpperCamelCase	,							return_tensors=_UpperCamelCase	,							**_UpperCamelCase      )




       def 	__snake_case(						self   :					List[Any]	,							_UpperCamelCase   :					List[Any]      )					->				Optional[Any]:



            '''simple docstring'''

            return self.model(**_UpperCamelCase      )





       def 	__snake_case(						self   :					Tuple	,							_UpperCamelCase   :					Tuple	,							_UpperCamelCase   :					Any=None	,							_UpperCamelCase   :					Optional[int]=1	,							_UpperCamelCase   :					Any=True      )					->				Tuple:



            '''simple docstring'''

            if function_to_apply is None:
                 if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
                      SCREAMING_SNAKE_CASE    			=       ClassificationFunction.SIGMOID
                 elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
                      SCREAMING_SNAKE_CASE    			=       ClassificationFunction.SOFTMAX
                 elif hasattr(self.model.config	,							"function_to_apply"      ) and function_to_apply is None:
                      SCREAMING_SNAKE_CASE    			=       self.model.config.function_to_apply
                 else:
                      SCREAMING_SNAKE_CASE    			=       ClassificationFunction.NONE

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

            if function_to_apply == ClassificationFunction.SIGMOID:
                 SCREAMING_SNAKE_CASE    			=       sigmoid(_UpperCamelCase      )
            elif function_to_apply == ClassificationFunction.SOFTMAX:
                 SCREAMING_SNAKE_CASE    			=       softmax(_UpperCamelCase      )
            elif function_to_apply == ClassificationFunction.NONE:
                 SCREAMING_SNAKE_CASE    			=       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()}

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





import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest


class 						lowercase    (     a     ):
							lowercase__						:       Tuple								=							(KDPMaDiscreteScheduler,)
							lowercase__						:       Optional[int]								=							10




							def 	__snake_case(						self   :					Optional[Any]	,							**_UpperCamelCase   :					List[Any]      )					->				Tuple:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       {
												    "num_train_timesteps": 1_100,
												    "beta_start": 0.0_0_0_1,
												    "beta_end": 0.0_2,
												    "beta_schedule": "linear",
												}

												config.update(**_UpperCamelCase      )
												return config




							def 	__snake_case(						self   :					int      )					->				List[Any]:



												'''simple docstring'''

												for timesteps in [10, 50, 100, 1_000]:
																	self.check_over_configs(num_train_timesteps=_UpperCamelCase      )




							def 	__snake_case(						self   :					Union[str, Any]      )					->				Union[str, Any]:



												'''simple docstring'''

												for beta_start, beta_end in zip([0.0_0_0_0_1, 0.0_0_0_1, 0.0_0_1]	,							[0.0_0_0_2, 0.0_0_2, 0.0_2]      ):
																	self.check_over_configs(beta_start=_UpperCamelCase	,							beta_end=_UpperCamelCase      )




							def 	__snake_case(						self   :					Union[str, Any]      )					->				str:



												'''simple docstring'''

												for schedule in ["linear", "scaled_linear"]:
																	self.check_over_configs(beta_schedule=_UpperCamelCase      )




							def 	__snake_case(						self   :					Optional[int]      )					->				int:



												'''simple docstring'''

												for prediction_type in ["epsilon", "v_prediction"]:
																	self.check_over_configs(prediction_type=_UpperCamelCase      )




							def 	__snake_case(						self   :					Optional[int]      )					->				Any:



												'''simple docstring'''

												SCREAMING_SNAKE_CASE    			=       self.scheduler_classes[0]
												SCREAMING_SNAKE_CASE    			=       self.get_scheduler_config(prediction_type="v_prediction"      )
												SCREAMING_SNAKE_CASE    			=       scheduler_class(**_UpperCamelCase      )

												scheduler.set_timesteps(self.num_inference_steps      )

												SCREAMING_SNAKE_CASE    			=       self.dummy_model()
												SCREAMING_SNAKE_CASE    			=       self.dummy_sample_deter * scheduler.init_noise_sigma
												SCREAMING_SNAKE_CASE    			=       sample.to(_UpperCamelCase      )

												for i, t in enumerate(scheduler.timesteps      ):
																	SCREAMING_SNAKE_CASE    			=       scheduler.scale_model_input(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       model(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       scheduler.step(_UpperCamelCase	,							_UpperCamelCase	,							_UpperCamelCase      )
																	SCREAMING_SNAKE_CASE    			=       output.prev_sample

												SCREAMING_SNAKE_CASE    			=       torch.sum(torch.abs(_UpperCamelCase      )      )
												SCREAMING_SNAKE_CASE    			=       torch.mean(torch.abs(_UpperCamelCase      )      )

												if torch_device in ["cpu", "mps"]:
																	assert abs(result_sum.item() - 4.6_934e-07      ) < 1e-2
																	assert abs(result_mean.item() - 6.1_112e-10      ) < 1e-3
												else:
																	# CUDA
																	assert abs(result_sum.item() - 4.693_428_650_170_972e-07      ) < 1e-2
																	assert abs(result_mean.item() - 0.0_0_0_2      ) < 1e-3




							def 	__snake_case(						self   :					Dict      )					->				int:



												'''simple docstring'''

												if torch_device == "mps":
																	return
												SCREAMING_SNAKE_CASE    			=       self.scheduler_classes[0]
												SCREAMING_SNAKE_CASE    			=       self.get_scheduler_config()
												SCREAMING_SNAKE_CASE    			=       scheduler_class(**_UpperCamelCase      )

												scheduler.set_timesteps(self.num_inference_steps      )

												SCREAMING_SNAKE_CASE    			=       self.dummy_model()
												SCREAMING_SNAKE_CASE    			=       self.dummy_sample_deter * scheduler.init_noise_sigma
												SCREAMING_SNAKE_CASE    			=       sample.to(_UpperCamelCase      )

												for i, t in enumerate(scheduler.timesteps      ):
																	SCREAMING_SNAKE_CASE    			=       scheduler.scale_model_input(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       model(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       scheduler.step(_UpperCamelCase	,							_UpperCamelCase	,							_UpperCamelCase      )
																	SCREAMING_SNAKE_CASE    			=       output.prev_sample

												SCREAMING_SNAKE_CASE    			=       torch.sum(torch.abs(_UpperCamelCase      )      )
												SCREAMING_SNAKE_CASE    			=       torch.mean(torch.abs(_UpperCamelCase      )      )

												if torch_device in ["cpu", "mps"]:
																	assert abs(result_sum.item() - 2_0.4_1_2_5      ) < 1e-2
																	assert abs(result_mean.item() - 0.0_2_6_6      ) < 1e-3
												else:
																	# CUDA
																	assert abs(result_sum.item() - 2_0.4_1_2_5      ) < 1e-2
																	assert abs(result_mean.item() - 0.0_2_6_6      ) < 1e-3





							def 	__snake_case(						self   :					Tuple      )					->				str:



												'''simple docstring'''

												if torch_device == "mps":
																	return
												SCREAMING_SNAKE_CASE    			=       self.scheduler_classes[0]
												SCREAMING_SNAKE_CASE    			=       self.get_scheduler_config()
												SCREAMING_SNAKE_CASE    			=       scheduler_class(**_UpperCamelCase      )

												scheduler.set_timesteps(self.num_inference_steps	,							device=_UpperCamelCase      )

												SCREAMING_SNAKE_CASE    			=       self.dummy_model()
												SCREAMING_SNAKE_CASE    			=       self.dummy_sample_deter.to(_UpperCamelCase      ) * scheduler.init_noise_sigma

												for t in scheduler.timesteps:
																	SCREAMING_SNAKE_CASE    			=       scheduler.scale_model_input(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       model(_UpperCamelCase	,							_UpperCamelCase      )

																	SCREAMING_SNAKE_CASE    			=       scheduler.step(_UpperCamelCase	,							_UpperCamelCase	,							_UpperCamelCase      )
																	SCREAMING_SNAKE_CASE    			=       output.prev_sample

												SCREAMING_SNAKE_CASE    			=       torch.sum(torch.abs(_UpperCamelCase      )      )
												SCREAMING_SNAKE_CASE    			=       torch.mean(torch.abs(_UpperCamelCase      )      )

												if str(_UpperCamelCase      ).startswith("cpu"      ):
																	# The following sum varies between 148 and 156 on mps. Why?
																	assert abs(result_sum.item() - 2_0.4_1_2_5      ) < 1e-2
																	assert abs(result_mean.item() - 0.0_2_6_6      ) < 1e-3
												else:
																	# CUDA
																	assert abs(result_sum.item() - 2_0.4_1_2_5      ) < 1e-2
																	assert abs(result_mean.item() - 0.0_2_6_6      ) < 1e-3




