




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


_snake_case										=       logging.get_logger(__name__)







class 						lowercase							(   _a		):

     def 					a__	(  self		,     _a				)						->							int:







           if isinstance(UpperCamelCase__		,     UpperCamelCase__				):
                 _A							:     Any			=						[label.strip() for label in labels.split(""","""				) if label.strip()]
           return labels



     def __call__(  self		,     _a		,     _a		,     _a				)						->							List[Any]:







           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							:     Any			=						[sequences]

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

           return sequence_pairs, sequences







@add_end_docstrings(_a		)
class 						lowercase							(   _a		):

     def __init__(  self		,     _a=ZeroShotClassificationArgumentHandler()		,     *_a		,     **_a				)						->							Union[str, Any]:
           _A							:     List[str]			=						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 					a__	(  self				)						->							List[str]:







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

     def 					a__	(  self		,     _a		,     _a=True		,     _a=True		,     _a=TruncationStrategy.ONLY_FIRST		,     **_a				)						->							Tuple:
           _A							:     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`"""				)
                 _A							:     Tuple			=						self.tokenizer.eos_token
           try:
                 _A							:     Any			=						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							:     List[str]			=						self.tokenizer(
                           UpperCamelCase__		,     add_special_tokens=UpperCamelCase__		,     return_tensors=UpperCamelCase__		,     padding=UpperCamelCase__		,     truncation=TruncationStrategy.DO_NOT_TRUNCATE		,     )
                 else:
                       raise e

           return inputs

     def 					a__	(  self		,     **_a				)						->							Dict:







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

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

     def __call__(  self		,     _a		,     *_a		,     **_a		,     )						->							int:







           if len(UpperCamelCase__				) == 0:
                 pass
           elif len(UpperCamelCase__				) == 1 and "candidate_labels" not in kwargs:
                 _A							:     Optional[int]			=						args[0]
           else:
                 raise ValueError(F'''Unable to understand extra arguments {args}'''				)

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

     def 					a__	(  self		,     _a		,     _a=None		,     _a="This example is {}."				)						->							Any:
           _A			,   _A							:     Dict			=						self._args_parser(UpperCamelCase__		,     UpperCamelCase__		,     UpperCamelCase__				)

           for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCamelCase__		,     UpperCamelCase__				)				):
                 _A							:     Union[str, Any]			=						self._parse_and_tokenize([sequence_pair]				)

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

     def 					a__	(  self		,     _a				)						->							Optional[Any]:
           _A							:     List[str]			=						inputs["""candidate_label"""]
           _A							:     Optional[int]			=						inputs["""sequence"""]
           _A							:     int			=						{k: inputs[k] for k in self.tokenizer.model_input_names}
           _A							:     List[str]			=						self.model(**UpperCamelCase__				)

           _A							:     Union[str, Any]			=						{
               """candidate_label""": candidate_label,
               """sequence""": sequence,
               """is_last""": inputs["""is_last"""],
               **outputs,
           }
           return model_outputs



     def 					a__	(  self		,     _a		,     _a=False				)						->							List[Any]:
           _A							:     Optional[int]			=						[outputs["""candidate_label"""] for outputs in model_outputs]
           _A							:     int			=						[outputs["""sequence"""] for outputs in model_outputs]
           _A							:     Union[str, Any]			=						np.concatenate([output["""logits"""].numpy() for output in model_outputs]				)
           _A							:     Any			=						logits.shape[0]
           _A							:     Tuple			=						len(UpperCamelCase__				)
           _A							:     Optional[int]			=						N // n
           _A							:     Optional[Any]			=						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							:     List[Any]			=						self.entailment_id
                 _A							:     List[Any]			=						-1 if entailment_id == 0 else 0
                 _A							:     Dict			=						reshaped_outputs[..., [contradiction_id, entailment_id]]
                 _A							:     Tuple			=						np.exp(UpperCamelCase__				) / np.exp(UpperCamelCase__				).sum(-1		,     keepdims=UpperCamelCase__				)
                 _A							:     Any			=						scores[..., 1]
           else:
                 # softmax the "entailment" logits over all candidate labels
                 _A							:     Optional[int]			=						reshaped_outputs[..., self.entailment_id]
                 _A							:     Optional[int]			=						np.exp(UpperCamelCase__				) / np.exp(UpperCamelCase__				).sum(-1		,     keepdims=UpperCamelCase__				)

           _A							:     str			=						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 warnings

from ...utils import logging
from .image_processing_chinese_clip import ChineseCLIPImageProcessor


_lowerCamelCase	:       str      	=	logging.get_logger(__name__)

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    def __init__(  self      :					Dict  ,						*UpperCamelCase__      :					List[Any]  ,						**UpperCamelCase__      :					List[Any] ):


       """simple docstring"""







       warnings.warn(
           'The class ChineseCLIPFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'
           ' Please use ChineseCLIPImageProcessor instead.'  ,						UpperCamelCase__  ,						)
       super().__init__(*UpperCamelCase__  ,						**UpperCamelCase__ )

