

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 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							def 				__lowercase				(			self       ,							_a       )    ->    Optional[Any]:
												if isinstance(_a       ,							_a       ):
																	_a	:    List[str]         =		[label.strip() for label in labels.split(''','''       ) if label.strip()]
												return labels




							def __call__(			self       ,							_a       ,							_a       ,							_a       )    ->    Optional[int]:
												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       ):
																	_a	:    Optional[int]         =		[sequences]

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

												return sequence_pairs, sequences



@add_end_docstrings(__lowercase   )
class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







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


							def 				__lowercase				(			self       ,							_a       ,							_a=True       ,							_a=True       ,							_a=TruncationStrategy.ONLY_FIRST       ,							**_a       )    ->    Tuple:
												_a	:    Optional[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	:    Dict         =		self.tokenizer.eos_token
												try:
																	_a	:    Dict         =		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.

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

												return inputs


							def 				__lowercase				(			self       ,							**_a       )    ->    str:
												if kwargs.get('''multi_class'''       ,							_a       ) 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	:    Union[str, Any]         =		{}
												if "candidate_labels" in kwargs:
																	_a	:    Optional[int]         =		self._args_parser._parse_labels(kwargs['''candidate_labels''']       )
												if "hypothesis_template" in kwargs:
																	_a	:    Union[str, Any]         =		kwargs['''hypothesis_template''']

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


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

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


							def 				__lowercase				(			self       ,							_a       ,							_a=None       ,							_a="This example is {}."       )    ->    str:
												_a      ,					_a	:    str         =		self._args_parser(_a       ,							_a       ,							_a       )

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

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


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

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




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

												_a	:    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(),
												}






import warnings

from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding

class 				UpperCAmelCase_		(			__lowercase   ):
							"""simple docstring"""







							UpperCAmelCase__       :						Union[str, Any]	    =    ["image_processor", "tokenizer"]
							UpperCAmelCase__       :						Dict	    =    "ChineseCLIPImageProcessor"
							UpperCAmelCase__       :						List[str]	    =    ("BertTokenizer", "BertTokenizerFast")


							def __init__(			self       ,							_a=None       ,							_a=None       ,							**_a       )    ->    Any:
												_a	:    Optional[Any]         =		None
												if "feature_extractor" in kwargs:
																	warnings.warn(
																	    '''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
																	    ''' instead.'''       ,							_a       ,							)
																	_a	:    Tuple         =		kwargs.pop('''feature_extractor'''       )

												_a	:    Tuple         =		image_processor if image_processor is not None else feature_extractor
												if image_processor is None:
																	raise ValueError('''You need to specify an `image_processor`.'''       )
												if tokenizer is None:
																	raise ValueError('''You need to specify a `tokenizer`.'''       )

												super().__init__(_a       ,							_a       )
												_a	:    List[str]         =		self.image_processor


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

												if text is None and images is None:
																	raise ValueError('''You have to specify either text or images. Both cannot be none.'''       )

												if text is not None:
																	_a	:    List[str]         =		self.tokenizer(_a       ,							return_tensors=_a       ,							**_a       )

												if images is not None:
																	_a	:    Optional[Any]         =		self.image_processor(_a       ,							return_tensors=_a       ,							**_a       )

												if text is not None and images is not None:
																	_a	:    Union[str, Any]         =		image_features.pixel_values
																	return encoding
												elif text is not None:
																	return encoding
												else:
																	return BatchEncoding(data=dict(**_a       )       ,							tensor_type=_a       )


							def 				__lowercase				(			self       ,							*_a       ,							**_a       )    ->    Union[str, Any]:
												return self.tokenizer.batch_decode(*_a       ,							**_a       )


							def 				__lowercase				(			self       ,							*_a       ,							**_a       )    ->    Any:
												return self.tokenizer.decode(*_a       ,							**_a       )


							@property
							def 				__lowercase				(			self       )    ->    Optional[Any]:
												_a	:    Any         =		self.tokenizer.model_input_names
												_a	:    Dict         =		self.image_processor.model_input_names
												return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names       )       )




							@property
							def 				__lowercase				(			self       )    ->    Dict:
												warnings.warn(
												    '''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.'''       ,							_a       ,							)
												return self.image_processor_class



