



"""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    : Union[str, Any]							=							logging.get_logger(__name__)






class      UpperCAmelCase_  (    _UpperCamelCase						):



      def 						snake_case_ (					self					:     Optional[Any]					,     A					:     Tuple						):
           if isinstance(A					,     A						):
                _UpperCAmelCase      :     Optional[int]        =   [label.strip() for label in labels.split(","						) if label.strip()]
           return labels



      def __call__(					self					:     List[Any]					,     A					:     List[str]					,     A					:     int					,     A					:     Optional[Any]						):
           if len(A						) == 0 or len(A						) == 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(A						)						)

           if isinstance(A					,     A						):
                _UpperCAmelCase      :     Optional[Any]        =   [sequences]

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

           return sequence_pairs, sequences







@add_end_docstrings(_UpperCamelCase						)
class      UpperCAmelCase_  (    _UpperCamelCase						):



      def __init__(					self					:     Any					,     A					:     int=ZeroShotClassificationArgumentHandler()					,     *A					:     List[str]					,     **A					:     Union[str, Any]						):
           _UpperCAmelCase      :     Tuple        =   args_parser
           super().__init__(*A					,     **A						)
           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 						snake_case_ (					self					:     Optional[int]						):
           for label, ind in self.model.config.labelaid.items():
                if label.lower().startswith("entail"						):
                     return ind
           return -1



      def 						snake_case_ (					self					:     Any					,     A					:     Optional[int]					,     A					:     List[str]=True					,     A					:     Dict=True					,     A					:     Union[str, Any]=TruncationStrategy.ONLY_FIRST					,     **A					:     Tuple						):
           _UpperCAmelCase      :     str        =   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`"						)
                _UpperCAmelCase      :     Any        =   self.tokenizer.eos_token
           try:
                _UpperCAmelCase      :     Optional[Any]        =   self.tokenizer(
                    A					,     add_special_tokens=A					,     return_tensors=A					,     padding=A					,     truncation=A					,     )
           except Exception as e:
                if "too short" in str(A						):
                     # 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.

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

           return inputs



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

           _UpperCAmelCase      :     List[Any]        =   {}
           if "multi_label" in kwargs:
                _UpperCAmelCase      :     Optional[int]        =   kwargs["multi_label"]
           return preprocess_params, {}, postprocess_params



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

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



      def 						snake_case_ (					self					:     Any					,     A					:     Any					,     A					:     Optional[int]=None					,     A					:     Tuple="This example is {}."						):
           _UpperCAmelCase    ,	_UpperCAmelCase      :     Optional[int]        =   self._args_parser(A					,     A					,     A						)

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

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



      def 						snake_case_ (					self					:     Tuple					,     A					:     Dict						):
           _UpperCAmelCase      :     int        =   inputs["candidate_label"]
           _UpperCAmelCase      :     Optional[int]        =   inputs["sequence"]
           _UpperCAmelCase      :     Tuple        =   {k: inputs[k] for k in self.tokenizer.model_input_names}
           _UpperCAmelCase      :     Optional[int]        =   self.model(**A						)

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



      def 						snake_case_ (					self					:     Optional[int]					,     A					:     str					,     A					:     str=False						):
           _UpperCAmelCase      :     List[str]        =   [outputs["candidate_label"] for outputs in model_outputs]
           _UpperCAmelCase      :     Tuple        =   [outputs["sequence"] for outputs in model_outputs]
           _UpperCAmelCase      :     Any        =   np.concatenate([output["logits"].numpy() for output in model_outputs]						)
           _UpperCAmelCase      :     Dict        =   logits.shape[0]
           _UpperCAmelCase      :     Optional[int]        =   len(A						)
           _UpperCAmelCase      :     Tuple        =   N // n
           _UpperCAmelCase      :     List[Any]        =   logits.reshape((num_sequences, n, -1)						)

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

           _UpperCAmelCase      :     Dict        =   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"""




from typing import Dict, Iterable, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


_lowerCAmelCase    : Tuple							=							logging.get_logger(__name__)






class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       str								=			['pixel_values']



      def __init__(					self					:     List[Any]					,     A					:     bool = True					,     A					:     Dict[str, int] = None					,     A					:     PILImageResampling = PILImageResampling.BICUBIC					,     A					:     bool = True					,     A					:     Dict[str, int] = None					,     A					:     bool = True					,     A					:     Union[int, float] = 1 / 2_5_5					,     A					:     bool = True					,     A					:     Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_MEAN					,     A					:     Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD					,     **A					:     List[Any]					,     ):
           super().__init__(**A						)
           _UpperCAmelCase      :     int        =   size if size is not None else {"shortest_edge": 2_2_4}
           _UpperCAmelCase      :     Tuple        =   get_size_dict(A					,     default_to_square=A						)
           _UpperCAmelCase      :     int        =   crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
           _UpperCAmelCase      :     Union[str, Any]        =   get_size_dict(A					,     param_name="crop_size"						)

           _UpperCAmelCase      :     str        =   do_resize
           _UpperCAmelCase      :     Union[str, Any]        =   size
           _UpperCAmelCase      :     Tuple        =   resample
           _UpperCAmelCase      :     List[Any]        =   do_center_crop
           _UpperCAmelCase      :     List[Any]        =   crop_size
           _UpperCAmelCase      :     Tuple        =   do_rescale
           _UpperCAmelCase      :     List[Any]        =   rescale_factor
           _UpperCAmelCase      :     Dict        =   do_normalize
           _UpperCAmelCase      :     Optional[Any]        =   image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
           _UpperCAmelCase      :     Any        =   image_std if image_std is not None else IMAGENET_DEFAULT_STD



      def 						snake_case_ (					self					:     Optional[int]					,     A					:     np.ndarray					,     A					:     Dict[str, int]					,     A					:     PILImageResampling = PILImageResampling.BICUBIC					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     Union[str, Any]					,     ):
           _UpperCAmelCase      :     Tuple        =   get_size_dict(A					,     default_to_square=A						)
           # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
           if "shortest_edge" in size:
                _UpperCAmelCase      :     Any        =   int((2_5_6 / 2_2_4) * size["shortest_edge"]						)
                _UpperCAmelCase      :     Union[str, Any]        =   get_resize_output_image_size(A					,     size=A					,     default_to_square=A						)
                _UpperCAmelCase      :     str        =   {"height": output_size[0], "width": output_size[1]}
           if "height" not in size_dict or "width" not in size_dict:
                raise ValueError(
                    f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'						)
           return resize(
               A					,     size=(size_dict["height"], size_dict["width"])					,     resample=A					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     int					,     A					:     np.ndarray					,     A					:     Dict[str, int]					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     Optional[Any]					,     ):
           _UpperCAmelCase      :     Dict        =   get_size_dict(A						)
           if "height" not in size or "width" not in size:
                raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'						)
           return center_crop(A					,     size=(size["height"], size["width"])					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     List[str]					,     A					:     np.ndarray					,     A					:     Union[int, float]					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     Dict					,     ):
           return rescale(A					,     scale=A					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     List[str]					,     A					:     np.ndarray					,     A					:     Union[float, List[float]]					,     A					:     Union[float, List[float]]					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     str					,     ):
           return normalize(A					,     mean=A					,     std=A					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     Tuple					,     A					:     ImageInput					,     A					:     Optional[bool] = None					,     A					:     Optional[Dict[str, int]] = None					,     A					:     PILImageResampling = None					,     A					:     Optional[bool] = None					,     A					:     Optional[Dict[str, int]] = None					,     A					:     Optional[bool] = None					,     A					:     Optional[float] = None					,     A					:     Optional[bool] = None					,     A					:     Optional[Union[float, Iterable[float]]] = None					,     A					:     Optional[Union[float, Iterable[float]]] = None					,     A					:     Optional[TensorType] = None					,     A					:     ChannelDimension = ChannelDimension.FIRST					,     **A					:     Dict					,     ):
           _UpperCAmelCase      :     Dict        =   do_resize if do_resize is not None else self.do_resize
           _UpperCAmelCase      :     List[str]        =   resample if resample is not None else self.resample
           _UpperCAmelCase      :     int        =   do_center_crop if do_center_crop is not None else self.do_center_crop
           _UpperCAmelCase      :     str        =   do_rescale if do_rescale is not None else self.do_rescale
           _UpperCAmelCase      :     Tuple        =   rescale_factor if rescale_factor is not None else self.rescale_factor
           _UpperCAmelCase      :     Optional[int]        =   do_normalize if do_normalize is not None else self.do_normalize
           _UpperCAmelCase      :     List[str]        =   image_mean if image_mean is not None else self.image_mean
           _UpperCAmelCase      :     Tuple        =   image_std if image_std is not None else self.image_std

           _UpperCAmelCase      :     Any        =   size if size is not None else self.size
           _UpperCAmelCase      :     Optional[int]        =   get_size_dict(A					,     default_to_square=A						)
           _UpperCAmelCase      :     List[str]        =   crop_size if crop_size is not None else self.crop_size
           _UpperCAmelCase      :     List[str]        =   get_size_dict(A					,     param_name="crop_size"						)

           _UpperCAmelCase      :     List[Any]        =   make_list_of_images(A						)

           if not valid_images(A						):
                raise ValueError(
                    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
                    "torch.Tensor, tf.Tensor or jax.ndarray."						)

           if do_resize and size is None:
                raise ValueError("Size must be specified if do_resize is True."						)

           if do_center_crop and crop_size is None:
                raise ValueError("Crop size must be specified if do_center_crop is True."						)

           if do_rescale and rescale_factor is None:
                raise ValueError("Rescale factor must be specified if do_rescale is True."						)

           if do_normalize and (image_mean is None or image_std is None):
                raise ValueError("Image mean and std must be specified if do_normalize is True."						)

           # All transformations expect numpy arrays.
           _UpperCAmelCase      :     Any        =   [to_numpy_array(A						) for image in images]

           if do_resize:
                _UpperCAmelCase      :     str        =   [self.resize(A					,     A					,     A						) for image in images]

           if do_center_crop:
                _UpperCAmelCase      :     Dict        =   [self.center_crop(A					,     A						) for image in images]

           if do_rescale:
                _UpperCAmelCase      :     Dict        =   [self.rescale(A					,     A						) for image in images]

           if do_normalize:
                _UpperCAmelCase      :     Optional[int]        =   [self.normalize(A					,     A					,     A						) for image in images]

           _UpperCAmelCase      :     Union[str, Any]        =   [to_channel_dimension_format(A					,     A						) for image in images]

           _UpperCAmelCase      :     List[Any]        =   {"pixel_values": images}
           return BatchFeature(data=A					,     tensor_type=A						)
