




"""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


a							      =     logging.get_logger(__name__)





class 							lowercase_			(	__lowerCAmelCase				):



 '''simple docstring'''

 def      lowerCAmelCase_				(					self			:			int       ,				_UpperCAmelCase			:			str						):
       if isinstance(_UpperCAmelCase       ,				_UpperCAmelCase						):
             _A     =  [label.strip() for label in labels.split(','						) if label.strip()]
       return labels



 def __call__(					self			:			Optional[Any]       ,				_UpperCAmelCase			:			str       ,				_UpperCAmelCase			:			Tuple       ,				_UpperCAmelCase			:			Tuple						):
       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						):
             _A     =  [sequences]

       _A     =  []
       for sequence in sequences:
             sequence_pairs.extend([[sequence, hypothesis_template.format(_UpperCAmelCase						)] for label in labels]						)

       return sequence_pairs, sequences





@add_end_docstrings(__lowerCAmelCase				)
class 							lowercase_			(	__lowerCAmelCase				):



 '''simple docstring'''

 def __init__(					self			:			Any       ,				_UpperCAmelCase			:			int=ZeroShotClassificationArgumentHandler()       ,				*_UpperCAmelCase			:			Dict       ,				**_UpperCAmelCase			:			Optional[int]						):
       _A     =  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      lowerCAmelCase_				(					self			:			int						):
       for label, ind in self.model.config.labelaid.items():
             if label.lower().startswith('entail'						):
                   return ind
       return -1

 def      lowerCAmelCase_				(					self			:			Union[str, Any]       ,				_UpperCAmelCase			:			List[Any]       ,				_UpperCAmelCase			:			str=True       ,				_UpperCAmelCase			:			List[str]=True       ,				_UpperCAmelCase			:			List[str]=TruncationStrategy.ONLY_FIRST       ,				**_UpperCAmelCase			:			Dict						):
       _A     =  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`'						)
             _A     =  self.tokenizer.eos_token
       try:
             _A     =  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.

                   _A     =  self.tokenizer(
                       _UpperCAmelCase       ,				add_special_tokens=_UpperCAmelCase       ,				return_tensors=_UpperCAmelCase       ,				padding=_UpperCAmelCase       ,				truncation=TruncationStrategy.DO_NOT_TRUNCATE       ,				)
             else:
                   raise e

       return inputs

 def      lowerCAmelCase_				(					self			:			int       ,				**_UpperCAmelCase			:			Tuple						):
       if kwargs.get('multi_class'       ,				_UpperCAmelCase						) is not None:
             _A     =  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.'						)
       _A     =  {}
       if "candidate_labels" in kwargs:
             _A     =  self._args_parser._parse_labels(kwargs['candidate_labels']						)
       if "hypothesis_template" in kwargs:
             _A     =  kwargs['hypothesis_template']

       _A     =  {}
       if "multi_label" in kwargs:
             _A     =  kwargs['multi_label']
       return preprocess_params, {}, postprocess_params

 def __call__(					self			:			Any       ,				_UpperCAmelCase			:			Union[str, List[str]]       ,				*_UpperCAmelCase			:			int       ,				**_UpperCAmelCase			:			Dict       ,				):
       if len(_UpperCAmelCase						) == 0:
             pass
       elif len(_UpperCAmelCase						) == 1 and "candidate_labels" not in kwargs:
             _A     =  args[0]
       else:
             raise ValueError(F'''Unable to understand extra arguments {args}'''						)

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

 def      lowerCAmelCase_				(					self			:			List[Any]       ,				_UpperCAmelCase			:			List[str]       ,				_UpperCAmelCase			:			Optional[int]=None       ,				_UpperCAmelCase			:			List[Any]="This example is {}."						):
       _A  ,       _A     =  self._args_parser(_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase						)

       for i, (candidate_label, sequence_pair) in enumerate(zip(_UpperCAmelCase       ,				_UpperCAmelCase						)						):
             _A     =  self._parse_and_tokenize([sequence_pair]						)

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

 def      lowerCAmelCase_				(					self			:			Optional[int]       ,				_UpperCAmelCase			:			int						):
       _A     =  inputs['candidate_label']
       _A     =  inputs['sequence']
       _A     =  {k: inputs[k] for k in self.tokenizer.model_input_names}
       _A     =  self.model(**_UpperCAmelCase						)

       _A     =  {
           'candidate_label': candidate_label,
           'sequence': sequence,
           'is_last': inputs['is_last'],
           **outputs,
       }
       return model_outputs



 def      lowerCAmelCase_				(					self			:			Union[str, Any]       ,				_UpperCAmelCase			:			Optional[Any]       ,				_UpperCAmelCase			:			Dict=False						):
       _A     =  [outputs['candidate_label'] for outputs in model_outputs]
       _A     =  [outputs['sequence'] for outputs in model_outputs]
       _A     =  np.concatenate([output['logits'].numpy() for output in model_outputs]						)
       _A     =  logits.shape[0]
       _A     =  len(_UpperCAmelCase						)
       _A     =  N // n
       _A     =  logits.reshape((num_sequences, n, -1)						)

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

       _A     =  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 datasets.utils.patching import _PatchedModuleObj, patch_submodule

from . import _test_patching

def 	_lowerCAmelCase (    ):
      import os as original_os
      from os import path as original_path
      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join

      lowercase__  =	'__test_patch_submodule_mock__'
      with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
            # Every way to access os.path.join must be patched, and the rest must stay untouched

            # check os.path.join
            assert isinstance(_test_patching.os    ,	_PatchedModuleObj						)
            assert isinstance(_test_patching.os.path    ,	_PatchedModuleObj						)
            assert _test_patching.os.path.join is mock

            # check path.join
            assert isinstance(_test_patching.path    ,	_PatchedModuleObj						)
            assert _test_patching.path.join is mock

            # check join
            assert _test_patching.join is mock

            # check that the other attributes are untouched
            assert _test_patching.os.rename is original_rename
            assert _test_patching.path.dirname is original_dirname
            assert _test_patching.os.path.dirname is original_dirname

            # Even renamed modules or objects must be patched

            # check renamed_os.path.join
            assert isinstance(_test_patching.renamed_os    ,	_PatchedModuleObj						)
            assert isinstance(_test_patching.renamed_os.path    ,	_PatchedModuleObj						)
            assert _test_patching.renamed_os.path.join is mock

            # check renamed_path.join
            assert isinstance(_test_patching.renamed_path    ,	_PatchedModuleObj						)
            assert _test_patching.renamed_path.join is mock

            # check renamed_join
            assert _test_patching.renamed_join is mock

            # check that the other attributes are untouched
            assert _test_patching.renamed_os.rename is original_rename
            assert _test_patching.renamed_path.dirname is original_dirname
            assert _test_patching.renamed_os.path.dirname is original_dirname

      # check that everthing is back to normal when the patch is over

      assert _test_patching.os is original_os
      assert _test_patching.path is original_path
      assert _test_patching.join is original_join

      assert _test_patching.renamed_os is original_os
      assert _test_patching.renamed_path is original_path
      assert _test_patching.renamed_join is original_join

def 	_lowerCAmelCase (    ):
      assert _test_patching.open is open

      lowercase__  =	'__test_patch_submodule_builtin_mock__'
      # _test_patching has "open" in its globals
      assert _test_patching.open is open
      with patch_submodule(_test_patching    ,	'open'    ,	A__						):
            assert _test_patching.open is mock

      # check that everthing is back to normal when the patch is over

      assert _test_patching.open is open

def 	_lowerCAmelCase (    ):
      # pandas.read_csv is not present in _test_patching
      lowercase__  =	'__test_patch_submodule_missing_mock__'
      with patch_submodule(_test_patching    ,	'pandas.read_csv'    ,	A__						):
            pass

def 	_lowerCAmelCase (    ):
      # builtin should always be mocked even if they're not in the globals
      # in case they're loaded at one point
      lowercase__  =	'__test_patch_submodule_missing_builtin_mock__'
      # _test_patching doesn't have "len" in its globals
      assert getattr(_test_patching    ,	'len'    ,	A__						) is None
      with patch_submodule(_test_patching    ,	'len'    ,	A__						):
            assert _test_patching.len is mock
      assert _test_patching.len is len

def 	_lowerCAmelCase (    ):
      lowercase__  =	'__test_patch_submodule_start_and_stop_mock__'
      lowercase__  =	patch_submodule(_test_patching    ,	'open'    ,	A__						)
      assert _test_patching.open is open
      patch.start()
      assert _test_patching.open is mock
      patch.stop()
      assert _test_patching.open is open

def 	_lowerCAmelCase (    ):
      from os import rename as original_rename
      from os.path import dirname as original_dirname
      from os.path import join as original_join

      lowercase__  =	'__test_patch_submodule_successive_join__'
      lowercase__  =	'__test_patch_submodule_successive_dirname__'
      lowercase__  =	'__test_patch_submodule_successive_rename__'
      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename

      with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
            with patch_submodule(_test_patching    ,	'os.rename'    ,	A__						):
                  with patch_submodule(_test_patching    ,	'os.path.dirname'    ,	A__						):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

    # try another order
      with patch_submodule(_test_patching    ,	'os.rename'    ,	A__						):
            with patch_submodule(_test_patching    ,	'os.path.join'    ,	A__						):
                  with patch_submodule(_test_patching    ,	'os.path.dirname'    ,	A__						):
                        assert _test_patching.os.path.join is mock_join
                        assert _test_patching.os.path.dirname is mock_dirname
                        assert _test_patching.os.rename is mock_rename

      assert _test_patching.os.path.join is original_join
      assert _test_patching.os.path.dirname is original_dirname
      assert _test_patching.os.rename is original_rename

def 	_lowerCAmelCase (    ):
      lowercase__  =	'__test_patch_submodule_doesnt_exist_mock__'
      with patch_submodule(_test_patching    ,	'__module_that_doesn_exist__.__attribute_that_doesn_exist__'    ,	A__						):
            pass
      with patch_submodule(_test_patching    ,	'os.__attribute_that_doesn_exist__'    ,	A__						):
            pass
