

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







class 				SCREAMING_SNAKE_CASE					(		a_       ):






					"""simple docstring"""



					def        __lowerCAmelCase (       self			:				Union[str, Any]   ,lowercase_			:				List[str]		):
						if isinstance(lowercase_   ,lowercase_		):
							lowerCAmelCase__	:						Optional[Any]  				=	[label.strip() for label in labels.split(''','''		) if label.strip()]
						return labels







					def __call__(       self			:				int   ,lowercase_			:				List[Any]   ,lowercase_			:				Optional[int]   ,lowercase_			:				List[Any]		):
						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_		):
							lowerCAmelCase__	:						Optional[Any]  				=	[sequences]

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

						return sequence_pairs, sequences







@add_end_docstrings(a_       )
class 				SCREAMING_SNAKE_CASE					(		a_       ):






					"""simple docstring"""



					def __init__(       self			:				List[str]   ,lowercase_			:				Optional[int]=ZeroShotClassificationArgumentHandler()   ,*lowercase_			:				Optional[int]   ,**lowercase_			:				str		):
						lowerCAmelCase__	:						Optional[int]  				=	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        __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]   ,lowercase_			:				Any   ,lowercase_			:				Optional[int]=True   ,lowercase_			:				Optional[Any]=True   ,lowercase_			:				List[str]=TruncationStrategy.ONLY_FIRST   ,**lowercase_			:				Optional[Any]		):
						lowerCAmelCase__	:						Dict  				=	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`'''		)
							lowerCAmelCase__	:						Any  				=	self.tokenizer.eos_token
						try:
							lowerCAmelCase__	:						Optional[Any]  				=	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.

								lowerCAmelCase__	:						Tuple  				=	self.tokenizer(
								    lowercase_   ,add_special_tokens=lowercase_   ,return_tensors=lowercase_   ,padding=lowercase_   ,truncation=TruncationStrategy.DO_NOT_TRUNCATE   ,)
							else:
								raise e

						return inputs







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

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







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

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







					def        __lowerCAmelCase (       self			:				Dict   ,lowercase_			:				str   ,lowercase_			:				Any=None   ,lowercase_			:				Optional[int]="This example is {}."		):
						lowerCAmelCase__				,lowerCAmelCase__	:						Union[str, Any]  				=	self._args_parser(lowercase_   ,lowercase_   ,lowercase_		)

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

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







					def        __lowerCAmelCase (       self			:				List[Any]   ,lowercase_			:				Optional[Any]		):
						lowerCAmelCase__	:						Optional[Any]  				=	inputs['''candidate_label''']
						lowerCAmelCase__	:						str  				=	inputs['''sequence''']
						lowerCAmelCase__	:						Tuple  				=	{k: inputs[k] for k in self.tokenizer.model_input_names}
						lowerCAmelCase__	:						Optional[int]  				=	self.model(**lowercase_		)

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







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

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

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





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,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


__UpperCamelCase  :      Optional[Any]							      =		logging.get_logger(__name__)


if is_vision_available():
							import PIL







class 				SCREAMING_SNAKE_CASE					(		a_       ):






					"""simple docstring"""



					lowercase__				 =       ["pixel_values"]







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

						lowerCAmelCase__	:						Dict  				=	do_resize
						lowerCAmelCase__	:						Optional[int]  				=	size
						lowerCAmelCase__	:						Dict  				=	resample
						lowerCAmelCase__	:						Optional[Any]  				=	do_center_crop
						lowerCAmelCase__	:						Dict  				=	crop_size
						lowerCAmelCase__	:						Tuple  				=	do_rescale
						lowerCAmelCase__	:						str  				=	rescale_factor
						lowerCAmelCase__	:						List[str]  				=	do_normalize
						lowerCAmelCase__	:						Tuple  				=	image_mean if image_mean is not None else OPENAI_CLIP_MEAN
						lowerCAmelCase__	:						Optional[Any]  				=	image_std if image_std is not None else OPENAI_CLIP_STD
						lowerCAmelCase__	:						Optional[Any]  				=	do_convert_rgb







					def        __lowerCAmelCase (       self			:				Dict   ,lowercase_			:				np.ndarray   ,lowercase_			:				Dict[str, int]   ,lowercase_			:				PILImageResampling = PILImageResampling.BICUBIC   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				Optional[Any]   ,):
						lowerCAmelCase__	:						Dict  				=	get_size_dict(lowercase_   ,default_to_square=lowercase_		)
						if "shortest_edge" not in size:
							raise ValueError(F'The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}'		)
						lowerCAmelCase__	:						Optional[Any]  				=	get_resize_output_image_size(lowercase_   ,size=size['''shortest_edge''']   ,default_to_square=lowercase_		)
						return resize(lowercase_   ,size=lowercase_   ,resample=lowercase_   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				Tuple   ,lowercase_			:				np.ndarray   ,lowercase_			:				Dict[str, int]   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				str   ,):
						lowerCAmelCase__	:						List[str]  				=	get_size_dict(lowercase_		)
						if "height" not in size or "width" not in size:
							raise ValueError(F'The `size` parameter must contain the keys (height, width). Got {size.keys()}'		)
						return center_crop(lowercase_   ,size=(size['''height'''], size['''width'''])   ,data_format=lowercase_   ,**lowercase_		)







					def        __lowerCAmelCase (       self			:				Optional[int]   ,lowercase_			:				np.ndarray   ,lowercase_			:				Union[int, float]   ,lowercase_			:				Optional[Union[str, ChannelDimension]] = None   ,**lowercase_			:				Union[str, Any]   ,):
						return rescale(lowercase_   ,scale=lowercase_   ,data_format=lowercase_   ,**lowercase_		)







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







					def        __lowerCAmelCase (       self			:				Optional[int]   ,lowercase_			:				ImageInput   ,lowercase_			:				bool = None   ,lowercase_			:				Dict[str, int] = None   ,lowercase_			:				PILImageResampling = None   ,lowercase_			:				bool = None   ,lowercase_			:				int = None   ,lowercase_			:				bool = None   ,lowercase_			:				float = None   ,lowercase_			:				bool = None   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,lowercase_			:				Optional[Union[float, List[float]]] = None   ,lowercase_			:				bool = None   ,lowercase_			:				Optional[Union[str, TensorType]] = None   ,lowercase_			:				Optional[ChannelDimension] = ChannelDimension.FIRST   ,**lowercase_			:				List[Any]   ,):
						lowerCAmelCase__	:						Optional[int]  				=	do_resize if do_resize is not None else self.do_resize
						lowerCAmelCase__	:						Optional[int]  				=	size if size is not None else self.size
						lowerCAmelCase__	:						Union[str, Any]  				=	get_size_dict(lowercase_   ,param_name='''size'''   ,default_to_square=lowercase_		)
						lowerCAmelCase__	:						Union[str, Any]  				=	resample if resample is not None else self.resample
						lowerCAmelCase__	:						Optional[Any]  				=	do_center_crop if do_center_crop is not None else self.do_center_crop
						lowerCAmelCase__	:						Optional[int]  				=	crop_size if crop_size is not None else self.crop_size
						lowerCAmelCase__	:						Dict  				=	get_size_dict(lowercase_   ,param_name='''crop_size'''   ,default_to_square=lowercase_		)
						lowerCAmelCase__	:						int  				=	do_rescale if do_rescale is not None else self.do_rescale
						lowerCAmelCase__	:						List[str]  				=	rescale_factor if rescale_factor is not None else self.rescale_factor
						lowerCAmelCase__	:						Optional[int]  				=	do_normalize if do_normalize is not None else self.do_normalize
						lowerCAmelCase__	:						str  				=	image_mean if image_mean is not None else self.image_mean
						lowerCAmelCase__	:						str  				=	image_std if image_std is not None else self.image_std
						lowerCAmelCase__	:						int  				=	do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

						lowerCAmelCase__	:						Any  				=	make_list_of_images(lowercase_		)

						if not valid_images(lowercase_		):
							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.'''		)

						# PIL RGBA images are converted to RGB
						if do_convert_rgb:
							lowerCAmelCase__	:						Tuple  				=	[convert_to_rgb(lowercase_		) for image in images]

						# All transformations expect numpy arrays.
						lowerCAmelCase__	:						Optional[int]  				=	[to_numpy_array(lowercase_		) for image in images]

						if do_resize:
							lowerCAmelCase__	:						Optional[int]  				=	[self.resize(image=lowercase_   ,size=lowercase_   ,resample=lowercase_		) for image in images]

						if do_center_crop:
							lowerCAmelCase__	:						Tuple  				=	[self.center_crop(image=lowercase_   ,size=lowercase_		) for image in images]

						if do_rescale:
							lowerCAmelCase__	:						Tuple  				=	[self.rescale(image=lowercase_   ,scale=lowercase_		) for image in images]

						if do_normalize:
							lowerCAmelCase__	:						Union[str, Any]  				=	[self.normalize(image=lowercase_   ,mean=lowercase_   ,std=lowercase_		) for image in images]

						lowerCAmelCase__	:						Optional[Any]  				=	[to_channel_dimension_format(lowercase_   ,lowercase_		) for image in images]

						lowerCAmelCase__	:						List[Any]  				=	{'''pixel_values''': images}
						return BatchFeature(data=lowercase_   ,tensor_type=lowercase_		)




