from collections import UserDict
from typing import List, Union

from ..utils import (
    add_end_docstrings,
    is_tf_available,
    is_torch_available,
    is_vision_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_vision_available():
		from PIL import Image

		from ..image_utils import load_image

if is_torch_available():
		from ..models.auto.modeling_auto import MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING

if is_tf_available():
		from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
		from ..tf_utils import stable_softmax

lowercase_		:				int				=						logging.get_logger(__name__)


@add_end_docstrings(_snake_case     )
class 			lowercase				(							_snake_case     ):



						"""simple docstring"""

						def __init__(    self			:		Union[str, Any] ,				**lowerCamelCase_			:		str					):





										'''simple docstring'''







										super().__init__(**lowerCamelCase_					)

										requires_backends(self ,				'vision'					)
										self.check_model_type(
										    TF_MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING
										    if self.framework == 'tf'
										    else MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING					)







						def __call__(    self			:		Dict ,				lowerCamelCase_			:		Union[str, List[str], "Image", List["Image"]] ,				**lowerCamelCase_			:		Optional[Any]					):





										'''simple docstring'''







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







						def 		__UpperCAmelCase       (    self			:		Optional[Any] ,				**lowerCamelCase_			:		Optional[int]					):





										'''simple docstring'''







										_snake_case :			Optional[int]  						=   {}
										if "candidate_labels" in kwargs:
														_snake_case :			Tuple  						=   kwargs['candidate_labels']
										if "hypothesis_template" in kwargs:
														_snake_case :			Tuple  						=   kwargs['hypothesis_template']

										return preprocess_params, {}, {}







						def 		__UpperCAmelCase       (    self			:		List[Any] ,				lowerCamelCase_			:		List[Any] ,				lowerCamelCase_			:		Union[str, Any]=None ,				lowerCamelCase_			:		Union[str, Any]="This is a photo of {}."					):





										'''simple docstring'''







										_snake_case :			str  						=   load_image(lowerCamelCase_					)
										_snake_case :			Optional[int]  						=   self.image_processor(images=[image] ,				return_tensors=self.framework					)
										_snake_case :			List[str]  						=   candidate_labels
										_snake_case :			Union[str, Any]  						=   [hypothesis_template.format(lowerCamelCase_					) for x in candidate_labels]
										_snake_case :			int  						=   self.tokenizer(lowerCamelCase_ ,				return_tensors=self.framework ,				padding=lowerCamelCase_					)
										_snake_case :			str  						=   [text_inputs]
										return inputs







						def 		__UpperCAmelCase       (    self			:		Tuple ,				lowerCamelCase_			:		str					):





										'''simple docstring'''







										_snake_case :			Tuple  						=   model_inputs.pop('candidate_labels'					)
										_snake_case :			int  						=   model_inputs.pop('text_inputs'					)
										if isinstance(text_inputs[0] ,				lowerCamelCase_					):
														_snake_case :			Dict  						=   text_inputs[0]
										else:
														# Batching case.
														_snake_case :			Any  						=   text_inputs[0][0]

										_snake_case :			str  						=   self.model(**lowerCamelCase_ ,				**lowerCamelCase_					)

										_snake_case :			List[Any]  						=   {
										    'candidate_labels': candidate_labels,
										    'logits': outputs.logits_per_image,
										}
										return model_outputs







						def 		__UpperCAmelCase       (    self			:		Dict ,				lowerCamelCase_			:		Tuple					):





										'''simple docstring'''







										_snake_case :			Any  						=   model_outputs.pop('candidate_labels'					)
										_snake_case :			Tuple  						=   model_outputs['logits'][0]
										if self.framework == "pt":
														_snake_case :			Dict  						=   logits.softmax(dim=-1					).squeeze(-1					)
														_snake_case :			Any  						=   probs.tolist()
														if not isinstance(lowerCamelCase_ ,				lowerCamelCase_					):
																		_snake_case :			List[str]  						=   [scores]
										elif self.framework == "tf":
														_snake_case :			List[Any]  						=   stable_softmax(lowerCamelCase_ ,				axis=-1					)
														_snake_case :			Optional[int]  						=   probs.numpy().tolist()
										else:
														raise ValueError(f'''Unsupported framework: {self.framework}'''					)

										_snake_case :			Any  						=   [
										    {'score': score, 'label': candidate_label}
										    for score, candidate_label in sorted(zip(lowerCamelCase_ ,				lowerCamelCase_					) ,				key=lambda lowerCamelCase_					: -x[0]					)
										]
										return result













from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowercase_		:				Any				=						{
    '''configuration_canine''': ['''CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CanineConfig'''],
    '''tokenization_canine''': ['''CanineTokenizer'''],
}

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase_		:				Optional[Any]				=						[
		    '''CANINE_PRETRAINED_MODEL_ARCHIVE_LIST''',
		    '''CanineForMultipleChoice''',
		    '''CanineForQuestionAnswering''',
		    '''CanineForSequenceClassification''',
		    '''CanineForTokenClassification''',
		    '''CanineLayer''',
		    '''CanineModel''',
		    '''CaninePreTrainedModel''',
		    '''load_tf_weights_in_canine''',
		]


if TYPE_CHECKING:
		from .configuration_canine import CANINE_PRETRAINED_CONFIG_ARCHIVE_MAP, CanineConfig
		from .tokenization_canine import CanineTokenizer

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_canine import (
				    CANINE_PRETRAINED_MODEL_ARCHIVE_LIST,
				    CanineForMultipleChoice,
				    CanineForQuestionAnswering,
				    CanineForSequenceClassification,
				    CanineForTokenClassification,
				    CanineLayer,
				    CanineModel,
				    CaninePreTrainedModel,
				    load_tf_weights_in_canine,
				)


else:
		import sys

		lowercase_		:				str				=						_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)






