





'''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_   :       Optional[int]       =     logging.get_logger(__name__)
class 							__SCREAMING_SNAKE_CASE    (SCREAMING_SNAKE_CASE__ ):






				"""simple docstring"""







				def     UpperCamelCase__  (    self	:   int   ,							__a	:   int   ):
								if isinstance(_lowercase   ,							_lowercase   ):
												_a				      =					[label.strip() for label in labels.split(","   ) if label.strip()]
								return labels




				def __call__(    self	:   Optional[Any]   ,							__a	:   Dict   ,							__a	:   Union[str, Any]   ,							__a	:   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   ):
												_a				      =					[sequences]

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

								return sequence_pairs, sequences


@add_end_docstrings(SCREAMING_SNAKE_CASE__ )
class 							__SCREAMING_SNAKE_CASE    (SCREAMING_SNAKE_CASE__ ):






				"""simple docstring"""







				def __init__(    self	:   List[str]   ,							__a	:   Union[str, Any]=ZeroShotClassificationArgumentHandler()   ,							*__a	:   List[Any]   ,							**__a	:   Union[str, Any]   ):
								_a				      =					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     UpperCamelCase__  (    self	:   str   ):
								for label, ind in self.model.config.labelaid.items():
												if label.lower().startswith("entail"   ):
																return ind
								return -1




				def     UpperCamelCase__  (    self	:   Optional[int]   ,							__a	:   List[Any]   ,							__a	:   Optional[Any]=True   ,							__a	:   int=True   ,							__a	:   Any=TruncationStrategy.ONLY_FIRST   ,							**__a	:   Optional[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(
												    _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.

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

								return inputs




				def     UpperCamelCase__  (    self	:   Tuple   ,							**__a	:   List[Any]   ):
								if kwargs.get("multi_class"   ,							_lowercase   ) 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	:   Optional[int]   ,							__a	:   Union[str, List[str]]   ,							*__a	:   Dict   ,							**__a	:   Optional[int]   ,							):
								if len(_lowercase   ) == 0:
												pass
								elif len(_lowercase   ) == 1 and "candidate_labels" not in kwargs:
												_a				      =					args[0]
								else:
												raise ValueError(f'Unable to understand extra arguments {args}'   )

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




				def     UpperCamelCase__  (    self	:   Optional[int]   ,							__a	:   List[str]   ,							__a	:   Dict=None   ,							__a	:   Union[str, Any]="This example is {}."   ):
								_a				      =					self._args_parser(_lowercase   ,							_lowercase   ,							_lowercase   )

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

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




				def     UpperCamelCase__  (    self	:   Union[str, Any]   ,							__a	:   Union[str, Any]   ):
								_a				      =					inputs["candidate_label"]
								_a				      =					inputs["sequence"]
								_a				      =					{k: inputs[k] for k in self.tokenizer.model_input_names}
								_a				      =					self.model(**_lowercase   )

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




				def     UpperCamelCase__  (    self	:   int   ,							__a	:   Union[str, Any]   ,							__a	:   Dict=False   ):
								_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(_lowercase   )
								_a				      =					N // n
								_a				      =					logits.reshape((num_sequences, n, -1)   )

								if multi_label or len(_lowercase   ) == 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(_lowercase   ) / np.exp(_lowercase   ).sum(-1   ,							keepdims=_lowercase   )
												_a				      =					scores[..., 1]
								else:
												# softmax the "entailment" logits over all candidate labels
												_a				      =					reshaped_outputs[..., self.entailment_id]
												_a				      =					np.exp(_lowercase   ) / np.exp(_lowercase   ).sum(-1   ,							keepdims=_lowercase   )

								_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 TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    is_vision_available,
)


A		=						{'configuration_vit': ['VIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTConfig', 'ViTOnnxConfig']}

try:
			if not is_vision_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						['ViTFeatureExtractor']
			A		=						['ViTImageProcessor']

try:
			if not is_torch_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'VIT_PRETRAINED_MODEL_ARCHIVE_LIST',
			    'ViTForImageClassification',
			    'ViTForMaskedImageModeling',
			    'ViTModel',
			    'ViTPreTrainedModel',
			]

try:
			if not is_tf_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'TFViTForImageClassification',
			    'TFViTModel',
			    'TFViTPreTrainedModel',
			]

try:
			if not is_flax_available():
						raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
			pass
else:
			A		=						[
			    'FlaxViTForImageClassification',
			    'FlaxViTModel',
			    'FlaxViTPreTrainedModel',
			]

if TYPE_CHECKING:
			from .configuration_vit import VIT_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTConfig, ViTOnnxConfig

			try:
						if not is_vision_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .feature_extraction_vit import ViTFeatureExtractor
						from .image_processing_vit import ViTImageProcessor

			try:
						if not is_torch_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_vit import (
						    VIT_PRETRAINED_MODEL_ARCHIVE_LIST,
						    ViTForImageClassification,
						    ViTForMaskedImageModeling,
						    ViTModel,
						    ViTPreTrainedModel,
						)

			try:
						if not is_tf_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_tf_vit import TFViTForImageClassification, TFViTModel, TFViTPreTrainedModel

			try:
						if not is_flax_available():
									raise OptionalDependencyNotAvailable()
			except OptionalDependencyNotAvailable:
						pass
			else:
						from .modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel, FlaxViTPreTrainedModel


else:
			import sys

			A		=						_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



