'''simple docstring'''





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   __A		(			_A					):



 """simple docstring"""


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



def   __A		(			_A					):



 """simple docstring"""


 __a       =  np.max(_outputs							,				axis=-1							,				keepdims=_snake_case					)
 __a       =  np.exp(_outputs - maxes					)
 return shifted_exp / shifted_exp.sum(axis=-1							,				keepdims=_snake_case					)
class    A_ (       __UpperCAmelCase ):
  _SCREAMING_SNAKE_CASE    				=			"""sigmoid"""
  _SCREAMING_SNAKE_CASE    				=			"""softmax"""
  _SCREAMING_SNAKE_CASE    				=			"""none"""
@add_end_docstrings(
    __UpperCAmelCase			,       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    A_ (       __UpperCAmelCase ):
  _SCREAMING_SNAKE_CASE    				=			False
  _SCREAMING_SNAKE_CASE    				=			ClassificationFunction.NONE

  def __init__(		self :      Union[str, Any]     ,							**__SCREAMING_SNAKE_CASE :      int       ):
   super().__init__(**UpperCAmelCase_       )

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

  def 		_UpperCAmelCase   (		self :      Tuple     ,							__SCREAMING_SNAKE_CASE :      Any=None     ,							__SCREAMING_SNAKE_CASE :      Tuple=None     ,							__SCREAMING_SNAKE_CASE :      Union[str, Any]=""     ,							**__SCREAMING_SNAKE_CASE :      Any       ):
   # 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(UpperCAmelCase_     ,							UpperCAmelCase_       ) 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`."     ,							UpperCAmelCase_     ,							)
    if return_all_scores:
     __a       =  None
    else:
     __a       =  1

   if isinstance(UpperCAmelCase_     ,							UpperCAmelCase_       ):
    __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 :      str     ,							*__SCREAMING_SNAKE_CASE :      Tuple     ,							**__SCREAMING_SNAKE_CASE :      int       ):
   __a       =  super().__call__(*UpperCAmelCase_     ,							**UpperCAmelCase_       )
   # TODO try and retrieve it in a nicer way from _sanitize_parameters.
   __a       =  "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 		_UpperCAmelCase   (		self :      List[str]     ,							__SCREAMING_SNAKE_CASE :      int     ,							**__SCREAMING_SNAKE_CASE :      Optional[int]       ):
   __a       =  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 		_UpperCAmelCase   (		self :      Dict     ,							__SCREAMING_SNAKE_CASE :      Optional[Any]       ):
   return self.model(**UpperCAmelCase_       )

  def 		_UpperCAmelCase   (		self :      Dict     ,							__SCREAMING_SNAKE_CASE :      List[str]     ,							__SCREAMING_SNAKE_CASE :      List[str]=None     ,							__SCREAMING_SNAKE_CASE :      List[Any]=1     ,							__SCREAMING_SNAKE_CASE :      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(UpperCAmelCase_       )
   elif function_to_apply == ClassificationFunction.SOFTMAX:
    __a       =  softmax(UpperCAmelCase_       )
   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(UpperCAmelCase_       )
   ]
   if not _legacy:
    dict_scores.sort(key=lambda __SCREAMING_SNAKE_CASE       : x["score"]     ,							reverse=UpperCAmelCase_       )
    if top_k is not None:
     __a       =  dict_scores[:top_k]
   return dict_scores



import unittest

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

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()
class    A_ (       unittest.TestCase ):

  @property
  def 		_UpperCAmelCase   (		self :      str       ):
   torch.manual_seed(0       )
   __a       =  UNetaDModel(
       block_out_channels=(32, 64)     ,							layers_per_block=2     ,							sample_size=32     ,							in_channels=3     ,							out_channels=3     ,							down_block_types=("DownBlock2D", "AttnDownBlock2D")     ,							up_block_types=("AttnUpBlock2D", "UpBlock2D")     ,							)
   return model

  @property
  def 		_UpperCAmelCase   (		self :      Dict       ):
   torch.manual_seed(0       )
   __a       =  VQModel(
       block_out_channels=[32, 64]     ,							in_channels=3     ,							out_channels=3     ,							down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]     ,							up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]     ,							latent_channels=3     ,							)
   return model

  @property
  def 		_UpperCAmelCase   (		self :      Optional[Any]       ):
   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=10_00     ,							)
   return CLIPTextModel(__SCREAMING_SNAKE_CASE       )

  def 		_UpperCAmelCase   (		self :      Dict       ):
   __a       =  self.dummy_uncond_unet
   __a       =  DDIMScheduler()
   __a       =  self.dummy_vq_model

   __a       =  LDMPipeline(unet=__SCREAMING_SNAKE_CASE     ,							vqvae=__SCREAMING_SNAKE_CASE     ,							scheduler=__SCREAMING_SNAKE_CASE       )
   ldm.to(__SCREAMING_SNAKE_CASE       )
   ldm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=2     ,							output_type="numpy"       ).images

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=2     ,							output_type="numpy"     ,							return_dict=__SCREAMING_SNAKE_CASE       )[0]

   __a       =  image[0, -3:, -3:, -1]
   __a       =  image_from_tuple[0, -3:, -3:, -1]

   assert image.shape == (1, 64, 64, 3)
   __a       =  np.array([0.85_12, 0.8_18, 0.64_11, 0.68_08, 0.44_65, 0.56_18, 0.46, 0.62_31, 0.51_72]       )
   __a       =  1E-2 if torch_device != "mps" else 3E-2

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
   assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance
@slow
@require_torch
class    A_ (       unittest.TestCase ):

  def 		_UpperCAmelCase   (		self :      str       ):
   __a       =  LDMPipeline.from_pretrained("CompVis/ldm-celebahq-256"       )
   ldm.to(__SCREAMING_SNAKE_CASE       )
   ldm.set_progress_bar_config(disable=__SCREAMING_SNAKE_CASE       )

   __a       =  torch.manual_seed(0       )
   __a       =  ldm(generator=__SCREAMING_SNAKE_CASE     ,							num_inference_steps=5     ,							output_type="numpy"       ).images

   __a       =  image[0, -3:, -3:, -1]

   assert image.shape == (1, 2_56, 2_56, 3)
   __a       =  np.array([0.43_99, 0.4_49_75, 0.4_68_25, 0.4_74, 0.43_59, 0.45_81, 0.4_50_95, 0.43_41, 0.44_47]       )
   __a       =  1E-2 if torch_device != "mps" else 3E-2

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance


