





'''simple docstring'''


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


lowerCAmelCase					:     Optional[int]												=logging.get_logger(__name__)
class       a_   (				_lowerCAmelCase							):





     def 							lowercase__      ( self		:					str	,      lowercase		:					Dict						):





        """simple docstring"""




        if isinstance(lowercase	,      lowercase						):
           lowercase_			:Dict    			= [label.strip() for label in labels.split(","						) if label.strip()]
        return labels







     def __call__( self		:					int	,      lowercase		:					int	,      lowercase		:					Union[str, Any]	,      lowercase		:					int						):





        """simple docstring"""




        if len(lowercase						) == 0 or len(lowercase						) == 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(lowercase						)						)

        if isinstance(lowercase	,      lowercase						):
           lowercase_			:List[str]    			= [sequences]

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

        return sequence_pairs, sequences







@add_end_docstrings(_lowerCAmelCase							)
class       a_   (				_lowerCAmelCase							):





     def __init__( self		:					List[Any]	,      lowercase		:					Tuple=ZeroShotClassificationArgumentHandler()	,      *lowercase		:					Dict	,      **lowercase		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:List[Any]    			= args_parser
        super().__init__(*lowercase	,      **lowercase						)
        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		:					Tuple						):





        """simple docstring"""




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





     def 							lowercase__      ( self		:					int	,      lowercase		:					Dict	,      lowercase		:					str=True	,      lowercase		:					Dict=True	,      lowercase		:					List[str]=TruncationStrategy.ONLY_FIRST	,      **lowercase		:					Optional[int]						):





        """simple docstring"""




        lowercase_			: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`"						)
           lowercase_			:Optional[Any]    			= self.tokenizer.eos_token
        try:
           lowercase_			:int    			= self.tokenizer(
               lowercase	,      add_special_tokens=lowercase	,      return_tensors=lowercase	,      padding=lowercase	,      truncation=lowercase	,      )
        except Exception as e:
           if "too short" in str(lowercase						):
              # 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.

              lowercase_			:List[str]    			= self.tokenizer(
                  lowercase	,      add_special_tokens=lowercase	,      return_tensors=lowercase	,      padding=lowercase	,      truncation=TruncationStrategy.DO_NOT_TRUNCATE	,      )
           else:
              raise e

        return inputs





     def 							lowercase__      ( self		:					int	,      **lowercase		:					str						):





        """simple docstring"""




        if kwargs.get("multi_class"	,      lowercase						) is not None:
           lowercase_			:Dict    			= 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."						)
        lowercase_			:Tuple    			= {}
        if "candidate_labels" in kwargs:
           lowercase_			:Optional[Any]    			= self._args_parser._parse_labels(kwargs["candidate_labels"]						)
        if "hypothesis_template" in kwargs:
           lowercase_			:List[str]    			= kwargs["hypothesis_template"]

        lowercase_			:Dict    			= {}
        if "multi_label" in kwargs:
           lowercase_			:int    			= kwargs["multi_label"]
        return preprocess_params, {}, postprocess_params





     def __call__( self		:					List[str]	,      lowercase		:					Union[str, List[str]]	,      *lowercase		:					Union[str, Any]	,      **lowercase		:					int	,      ):





        """simple docstring"""




        if len(lowercase						) == 0:
           pass
        elif len(lowercase						) == 1 and "candidate_labels" not in kwargs:
           lowercase_			:List[Any]    			= args[0]
        else:
           raise ValueError(F'Unable to understand extra arguments {args}'						)

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





     def 							lowercase__      ( self		:					Union[str, Any]	,      lowercase		:					Optional[int]	,      lowercase		:					Union[str, Any]=None	,      lowercase		:					List[str]="This example is {}."						):





        """simple docstring"""




        lowercase_			,							lowercase_			:List[Any]    			= self._args_parser(lowercase	,      lowercase	,      lowercase						)

        for i, (candidate_label, sequence_pair) in enumerate(zip(lowercase	,      lowercase						)						):
           lowercase_			:Optional[int]    			= self._parse_and_tokenize([sequence_pair]						)

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





     def 							lowercase__      ( self		:					Tuple	,      lowercase		:					int						):





        """simple docstring"""




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

        lowercase_			:List[Any]    			= {
            "candidate_label": candidate_label,
            "sequence": sequence,
            "is_last": inputs["is_last"],
            **outputs,
        }
        return model_outputs







     def 							lowercase__      ( self		:					Tuple	,      lowercase		:					int	,      lowercase		:					int=False						):





        """simple docstring"""




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

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

        lowercase_			: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(),
        }









'''simple docstring'''


import unittest

from transformers.testing_utils import CaptureStdout
from transformers.tools.python_interpreter import evaluate
def 							UpperCAmelCase_  (						__lowerCamelCase					:					List[Any] ):
   return x + 2


class       a_   (				unittest.TestCase							):





     def 							lowercase__      ( self		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3"
        lowercase_			:Any    			= {}
        lowercase_			:Any    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3}						)

        lowercase_			:Dict    			= "x = y"
        lowercase_			:Dict    			= {"y": 5}
        lowercase_			:str    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 5, "y": 5}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:Dict    			= "y = add_two(x)"
        lowercase_			:Optional[Any]    			= {"x": 3}
        lowercase_			:int    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)

        # Won't work without the tool
        with CaptureStdout() as out:
           lowercase_			:List[Any]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result is None
        assert "tried to execute add_two" in out.out





     def 							lowercase__      ( self		:					int						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3"
        lowercase_			:Any    			= {}
        lowercase_			:Any    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3}						)





     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:Optional[Any]    			= "test_dict = {'x': x, 'y': add_two(x)}"
        lowercase_			:List[str]    			= {"x": 3}
        lowercase_			:Any    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)
        self.assertDictEqual(lowercase	,      {"x": 3, "test_dict": {"x": 3, "y": 5}}						)





     def 							lowercase__      ( self		:					Optional[Any]						):





        """simple docstring"""




        lowercase_			:Optional[int]    			= "x = 3\ny = 5"
        lowercase_			:Union[str, Any]    			= {}
        lowercase_			:Optional[int]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 5}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:List[str]    			= "text = f'This is x: {x}.'"
        lowercase_			:int    			= {"x": 3}
        lowercase_			:int    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == "This is x: 3."
        self.assertDictEqual(lowercase	,      {"x": 3, "text": "This is x: 3."}						)





     def 							lowercase__      ( self		:					Optional[int]						):





        """simple docstring"""




        lowercase_			:List[Any]    			= "if x <= 3:\n    y = 2\nelse:\n    y = 5"
        lowercase_			:List[str]    			= {"x": 3}
        lowercase_			:Union[str, Any]    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 2
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 2}						)

        lowercase_			:List[str]    			= {"x": 8}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        # evaluate returns the value of the last assignment.
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 8, "y": 5}						)





     def 							lowercase__      ( self		:					Dict						):





        """simple docstring"""




        lowercase_			:Any    			= "test_list = [x, add_two(x)]"
        lowercase_			:Optional[int]    			= {"x": 3}
        lowercase_			:List[str]    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        self.assertListEqual(lowercase	,      [3, 5]						)
        self.assertDictEqual(lowercase	,      {"x": 3, "test_list": [3, 5]}						)





     def 							lowercase__      ( self		:					List[Any]						):





        """simple docstring"""




        lowercase_			:str    			= "y = x"
        lowercase_			:Any    			= {"x": 3}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {}	,      state=lowercase						)
        assert result == 3
        self.assertDictEqual(lowercase	,      {"x": 3, "y": 3}						)





     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:List[Any]    			= "test_list = [x, add_two(x)]\ntest_list[1]"
        lowercase_			:Dict    			= {"x": 3}
        lowercase_			:Any    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "test_list": [3, 5]}						)

        lowercase_			:Union[str, Any]    			= "test_dict = {'x': x, 'y': add_two(x)}\ntest_dict['y']"
        lowercase_			:List[Any]    			= {"x": 3}
        lowercase_			:List[Any]    			= evaluate(lowercase	,      {"add_two": add_two}	,      state=lowercase						)
        assert result == 5
        self.assertDictEqual(lowercase	,      {"x": 3, "test_dict": {"x": 3, "y": 5}}						)







     def 							lowercase__      ( self		:					Any						):





        """simple docstring"""




        lowercase_			:Dict    			= "x = 0\nfor i in range(3):\n    x = i"
        lowercase_			:Any    			= {}
        lowercase_			:Tuple    			= evaluate(lowercase	,      {"range": range}	,      state=lowercase						)
        assert result == 2
        self.assertDictEqual(lowercase	,      {"x": 2, "i": 2}						)


