




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


UpperCAmelCase_ 		=      logging.get_logger(__name__)





class    __lowercase						(  __A ):







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      )				->    Optional[int]:

     if isinstance(UpperCamelCase      ,							UpperCamelCase      ):
       __a			=					[label.strip() for label in labels.split(','      ) if label.strip()]
     return labels







   def __call__(	self      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase      )				->    Dict:

     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(__A )
class    __lowercase						(  __A ):







   def __init__(	self      ,							UpperCamelCase=ZeroShotClassificationArgumentHandler()      ,							*UpperCamelCase      ,							**UpperCamelCase      )				->    str:
     __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 		UpperCamelCase__			(	self      )				->    Union[str, Any]:

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







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase=True      ,							UpperCamelCase=True      ,							UpperCamelCase=TruncationStrategy.ONLY_FIRST      ,							**UpperCamelCase      )				->    int:
     __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 		UpperCamelCase__			(	self      ,							**UpperCamelCase      )				->    List[str]:

     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      ,							UpperCamelCase      ,							*UpperCamelCase      ,							**UpperCamelCase      ,							)				->    Optional[int]:

     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 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase=None      ,							UpperCamelCase="This example is {}."      )				->    Optional[int]:
     __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 		UpperCamelCase__			(	self      ,							UpperCamelCase      )				->    Dict:
     __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 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase=False      )				->    Union[str, Any]:
     __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(),
     }









'''simple docstring'''


from typing import Dict, 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_STANDARD_MEAN,
    IMAGENET_STANDARD_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
  import PIL


UpperCAmelCase_ 		=      logging.get_logger(__name__)





class    __lowercase						(  __magic_name__ ):
   _a							=      ["""pixel_values"""]







   def __init__(	self      ,							UpperCamelCase = True      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = PILImageResampling.BILINEAR      ,							UpperCamelCase = True      ,							UpperCamelCase = 1 / 255      ,							UpperCamelCase = True      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							**UpperCamelCase      ,							)				->    None:
     super().__init__(**UpperCamelCase      )
     __a			=					size if size is not None else {'shortest_edge': 384}
     __a			=					get_size_dict(UpperCamelCase      ,							default_to_square=UpperCamelCase      )

     __a			=					do_resize
     __a			=					size
     # Default value set here for backwards compatibility where the value in config is None
     __a			=					crop_pct if crop_pct is not None else 224 / 256
     __a			=					resample
     __a			=					do_rescale
     __a			=					rescale_factor
     __a			=					do_normalize
     __a			=					image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
     __a			=					image_std if image_std is not None else IMAGENET_STANDARD_STD







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase = PILImageResampling.BICUBIC      ,							UpperCamelCase = None      ,							**UpperCamelCase      ,							)				->    np.ndarray:
     __a			=					get_size_dict(UpperCamelCase      ,							default_to_square=UpperCamelCase      )
     if "shortest_edge" not in size:
       raise ValueError(f"Size dictionary must contain 'shortest_edge' key. Got {size.keys()}"      )
     __a			=					size['shortest_edge']

     if shortest_edge < 384:
       # maintain same ratio, resizing shortest edge to shortest_edge/crop_pct
       __a			=					int(shortest_edge / crop_pct      )
       __a			=					get_resize_output_image_size(UpperCamelCase      ,							size=UpperCamelCase      ,							default_to_square=UpperCamelCase      )
       __a			=					resize(image=UpperCamelCase      ,							size=UpperCamelCase      ,							resample=UpperCamelCase      ,							data_format=UpperCamelCase      ,							**UpperCamelCase      )
       # then crop to (shortest_edge, shortest_edge)
       return center_crop(image=UpperCamelCase      ,							size=(shortest_edge, shortest_edge)      ,							data_format=UpperCamelCase      ,							**UpperCamelCase      )
     else:
       # warping (no cropping) when evaluated at 384 or larger
       return resize(
           UpperCamelCase      ,							size=(shortest_edge, shortest_edge)      ,							resample=UpperCamelCase      ,							data_format=UpperCamelCase      ,							**UpperCamelCase      )







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase = None      ,							**UpperCamelCase      ,							)				->    Any:
     return rescale(UpperCamelCase      ,							scale=UpperCamelCase      ,							data_format=UpperCamelCase      ,							**UpperCamelCase      )







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase      ,							UpperCamelCase = None      ,							**UpperCamelCase      ,							)				->    np.ndarray:
     return normalize(UpperCamelCase      ,							mean=UpperCamelCase      ,							std=UpperCamelCase      ,							data_format=UpperCamelCase      ,							**UpperCamelCase      )







   def 		UpperCamelCase__			(	self      ,							UpperCamelCase      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = None      ,							UpperCamelCase = ChannelDimension.FIRST      ,							**UpperCamelCase      ,							)				->    PIL.Image.Image:
     __a			=					do_resize if do_resize is not None else self.do_resize
     __a			=					crop_pct if crop_pct is not None else self.crop_pct
     __a			=					resample if resample is not None else self.resample
     __a			=					do_rescale if do_rescale is not None else self.do_rescale
     __a			=					rescale_factor if rescale_factor is not None else self.rescale_factor
     __a			=					do_normalize if do_normalize is not None else self.do_normalize
     __a			=					image_mean if image_mean is not None else self.image_mean
     __a			=					image_std if image_std is not None else self.image_std

     __a			=					size if size is not None else self.size
     __a			=					get_size_dict(UpperCamelCase      ,							default_to_square=UpperCamelCase      )

     __a			=					make_list_of_images(UpperCamelCase      )

     if not valid_images(UpperCamelCase      ):
       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 or resample is None:
       raise ValueError('Size and resample must be specified if do_resize is True.'      )

     if do_resize and size["shortest_edge"] < 384 and crop_pct is None:
       raise ValueError('crop_pct must be specified if size < 384.'      )

     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.
     __a			=					[to_numpy_array(UpperCamelCase      ) for image in images]

     if do_resize:
       __a			=					[self.resize(image=UpperCamelCase      ,							size=UpperCamelCase      ,							crop_pct=UpperCamelCase      ,							resample=UpperCamelCase      ) for image in images]

     if do_rescale:
       __a			=					[self.rescale(image=UpperCamelCase      ,							scale=UpperCamelCase      ) for image in images]

     if do_normalize:
       __a			=					[self.normalize(image=UpperCamelCase      ,							mean=UpperCamelCase      ,							std=UpperCamelCase      ) for image in images]

     __a			=					[to_channel_dimension_format(UpperCamelCase      ,							UpperCamelCase      ) for image in images]

     __a			=					{'pixel_values': images}
     return BatchFeature(data=UpperCamelCase      ,							tensor_type=UpperCamelCase      )



