

from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


UpperCAmelCase__ :     Union[str, Any]				    =    logging.get_logger(__name__)







class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  def  _lowercase      (			self    : Optional[Any]				,				UpperCAmelCase__    : Tuple		)					->int:
        """simple docstring"""







        if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		):
              SCREAMING_SNAKE_CASE :      Optional[int]       =   [label.strip() for label in labels.split(""","""		) if label.strip()]
        return labels




  def __call__(			self    : Union[str, Any]				,				UpperCAmelCase__    : Union[str, Any]				,				UpperCAmelCase__    : str				,				UpperCAmelCase__    : int		)					->int:
        """simple docstring"""







        if len(UpperCAmelCase__		) == 0 or len(UpperCAmelCase__		) == 0:
              raise ValueError("""You must include at least one label and at least one sequence."""		)
        if hypothesis_template.format(labels[0]		) == hypothesis_template:
              raise ValueError(
                  (
                      """The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. """
                      """Make sure the passed template includes formatting syntax such as {{}} where the label should go."""
                  ).format(UpperCAmelCase__		)		)

        if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		):
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   [sequences]

        SCREAMING_SNAKE_CASE :      str       =   []
        for sequence in sequences:
              sequence_pairs.extend([[sequence, hypothesis_template.format(UpperCAmelCase__		)] for label in labels]		)

        return sequence_pairs, sequences







@add_end_docstrings(UpperCAmelCase       )
class        a__       (   UpperCAmelCase       ):







  """simple docstring"""




  def __init__(			self    : str				,				UpperCAmelCase__    : Optional[Any]=ZeroShotClassificationArgumentHandler()				,				*UpperCAmelCase__    : Dict				,				**UpperCAmelCase__    : List[str]		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Any       =   args_parser
        super().__init__(*UpperCAmelCase__				,				**UpperCAmelCase__		)
        if self.entailment_id == -1:
              logger.warning(
                  """Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to """
                  """-1. Define a descriptive label2id mapping in the model config to ensure correct outputs."""		)


  @property
  def  _lowercase      (			self    : Union[str, Any]		)					->Any:
        """simple docstring"""







        for label, ind in self.model.config.labelaid.items():
              if label.lower().startswith("""entail"""		):
                    return ind
        return -1


  def  _lowercase      (			self    : Dict				,				UpperCAmelCase__    : Optional[int]				,				UpperCAmelCase__    : Dict=True				,				UpperCAmelCase__    : Union[str, Any]=True				,				UpperCAmelCase__    : List[Any]=TruncationStrategy.ONLY_FIRST				,				**UpperCAmelCase__    : Optional[Any]		)					->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Optional[int]       =   self.framework
        if self.tokenizer.pad_token is None:
              # Override for tokenizers not supporting padding
              logger.error(
                  """Tokenizer was not supporting padding necessary for zero-shot, attempting to use """
                  """ `pad_token=eos_token`"""		)
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.tokenizer.eos_token
        try:
              SCREAMING_SNAKE_CASE :      str       =   self.tokenizer(
                  UpperCAmelCase__				,				add_special_tokens=UpperCAmelCase__				,				return_tensors=UpperCAmelCase__				,				padding=UpperCAmelCase__				,				truncation=UpperCAmelCase__				,				)
        except Exception as e:
              if "too short" in str(UpperCAmelCase__		):
                    # tokenizers might yell that we want to truncate
                    # to a value that is not even reached by the input.
                    # In that case we don't want to truncate.
                    # It seems there's not a really better way to catch that
                    # exception.

                    SCREAMING_SNAKE_CASE :      Any       =   self.tokenizer(
                        UpperCAmelCase__				,				add_special_tokens=UpperCAmelCase__				,				return_tensors=UpperCAmelCase__				,				padding=UpperCAmelCase__				,				truncation=TruncationStrategy.DO_NOT_TRUNCATE				,				)
              else:
                    raise e

        return inputs


  def  _lowercase      (			self    : Dict				,				**UpperCAmelCase__    : List[str]		)					->str:
        """simple docstring"""







        if kwargs.get("""multi_class"""				,				UpperCAmelCase__		) is not None:
              SCREAMING_SNAKE_CASE :      Optional[int]       =   kwargs["""multi_class"""]
              logger.warning(
                  """The `multi_class` argument has been deprecated and renamed to `multi_label`. """
                  """`multi_class` will be removed in a future version of Transformers."""		)
        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   {}
        if "candidate_labels" in kwargs:
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self._args_parser._parse_labels(kwargs["""candidate_labels"""]		)
        if "hypothesis_template" in kwargs:
              SCREAMING_SNAKE_CASE :      List[str]       =   kwargs["""hypothesis_template"""]

        SCREAMING_SNAKE_CASE :      Any       =   {}
        if "multi_label" in kwargs:
              SCREAMING_SNAKE_CASE :      Union[str, Any]       =   kwargs["""multi_label"""]
        return preprocess_params, {}, postprocess_params


  def __call__(			self    : List[str]				,				UpperCAmelCase__    : Union[str, List[str]]				,				*UpperCAmelCase__    : List[str]				,				**UpperCAmelCase__    : Dict				,				)					->Optional[Any]:
        """simple docstring"""







        if len(UpperCAmelCase__		) == 0:
              pass
        elif len(UpperCAmelCase__		) == 1 and "candidate_labels" not in kwargs:
              SCREAMING_SNAKE_CASE :      Dict       =   args[0]
        else:
              raise ValueError(f"Unable to understand extra arguments {args}"		)

        return super().__call__(UpperCAmelCase__				,				**UpperCAmelCase__		)


  def  _lowercase      (			self    : str				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : Tuple=None				,				UpperCAmelCase__    : Optional[Any]="This example is {}."		)					->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE     ,	SCREAMING_SNAKE_CASE :      Any       =   self._args_parser(UpperCAmelCase__				,				UpperCAmelCase__				,				UpperCAmelCase__		)

        for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCAmelCase__				,				UpperCAmelCase__		)		):
              SCREAMING_SNAKE_CASE :      Tuple       =   self._parse_and_tokenize([sequence_pair]		)

              yield {
                  "candidate_label": candidate_label,
                  "sequence": sequences[0],
                  "is_last": i == len(UpperCAmelCase__		) - 1,
                  **model_input,
              }


  def  _lowercase      (			self    : Union[str, Any]				,				UpperCAmelCase__    : int		)					->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   inputs["""candidate_label"""]
        SCREAMING_SNAKE_CASE :      Any       =   inputs["""sequence"""]
        SCREAMING_SNAKE_CASE :      str       =   {k: inputs[k] for k in self.tokenizer.model_input_names}
        SCREAMING_SNAKE_CASE :      Tuple       =   self.model(**UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      int       =   {
            """candidate_label""": candidate_label,
            """sequence""": sequence,
            """is_last""": inputs["""is_last"""],
            **outputs,
        }
        return model_outputs




  def  _lowercase      (			self    : Dict				,				UpperCAmelCase__    : Any				,				UpperCAmelCase__    : Union[str, Any]=False		)					->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[Any]       =   [outputs["""candidate_label"""] for outputs in model_outputs]
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   [outputs["""sequence"""] for outputs in model_outputs]
        SCREAMING_SNAKE_CASE :      str       =   np.concatenate([output["""logits"""].numpy() for output in model_outputs]		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   logits.shape[0]
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   len(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE :      List[Any]       =   N // n
        SCREAMING_SNAKE_CASE :      List[str]       =   logits.reshape((num_sequences, n, -1)		)

        if multi_label or len(UpperCAmelCase__		) == 1:
              # softmax over the entailment vs. contradiction dim for each label independently
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.entailment_id
              SCREAMING_SNAKE_CASE :      str       =   -1 if entailment_id == 0 else 0
              SCREAMING_SNAKE_CASE :      Optional[int]       =   reshaped_outputs[..., [contradiction_id, entailment_id]]
              SCREAMING_SNAKE_CASE :      List[Any]       =   np.exp(UpperCAmelCase__		) / np.exp(UpperCAmelCase__		).sum(-1				,				keepdims=UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE :      List[Any]       =   scores[..., 1]
        else:
              # softmax the "entailment" logits over all candidate labels
              SCREAMING_SNAKE_CASE :      int       =   reshaped_outputs[..., self.entailment_id]
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   np.exp(UpperCAmelCase__		) / np.exp(UpperCAmelCase__		).sum(-1				,				keepdims=UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE :      Tuple       =   list(reversed(scores[0].argsort()		)		)
        return {
            "sequence": sequences[0],
            "labels": [candidate_labels[i] for i in top_inds],
            "scores": scores[0, top_inds].tolist(),
        }







from typing import Any

import numpy as np






def 					__lowercase      (     _A			)     ->						bool:
      return np.array_equal(_A						,    matrix.conjugate().T			)






def 					__lowercase      (     _A						,    _A			)     ->						Any:
      SCREAMING_SNAKE_CASE :      Optional[int]       =   v.conjugate().T
      SCREAMING_SNAKE_CASE :      List[Any]       =   v_star.dot(_A			)
      assert isinstance(_A						,    np.ndarray			)
      return (v_star_dot.dot(_A			)) / (v_star.dot(_A			))






def 					__lowercase      (     )     ->						None:
      SCREAMING_SNAKE_CASE :      Any       =   np.array([[2, 2 + 1J, 4], [2 - 1J, 3, 1J], [4, -1J, 1]]			)
      SCREAMING_SNAKE_CASE :      Optional[int]       =   np.array([[1], [2], [3]]			)
      assert is_hermitian(_A			), F"{a} is not hermitian."
      print(rayleigh_quotient(_A						,    _A			)			)

      SCREAMING_SNAKE_CASE :      Any       =   np.array([[1, 2, 4], [2, 3, -1], [4, -1, 1]]			)
      assert is_hermitian(_A			), F"{a} is not hermitian."
      assert rayleigh_quotient(_A						,    _A			) == float(3			)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  tests()




