'''simple docstring'''




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

__UpperCAmelCase     							=logging.get_logger(__name__)




@add_end_docstrings(UpperCAmelCase__ )
class     a__      (   UpperCAmelCase__ ):






     def __init__( self		:		str  ,				**a		:		List[Any]    ):





         """simple docstring"""



         super().__init__(**a    )

         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  ,				a		:		Union[str, List[str], "Image", List["Image"]]  ,				**a		:		Dict    ):





         """simple docstring"""



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






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[Any]  ,				**a		:		Optional[Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  {}
         if "candidate_labels" in kwargs:
             __lowerCamelCase		=  kwargs['''candidate_labels''']
         if "hypothesis_template" in kwargs:
             __lowerCamelCase		=  kwargs['''hypothesis_template''']

         return preprocess_params, {}, {}






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





         """simple docstring"""



         __lowerCamelCase		=  load_image(a    )
         __lowerCamelCase		=  self.image_processor(images=[image]  ,				return_tensors=self.framework    )
         __lowerCamelCase		=  candidate_labels
         __lowerCamelCase		=  [hypothesis_template.format(a    ) for x in candidate_labels]
         __lowerCamelCase		=  self.tokenizer(a  ,				return_tensors=self.framework  ,				padding=a    )
         __lowerCamelCase		=  [text_inputs]
         return inputs






     def    SCREAMING_SNAKE_CASE__   ( self		:		Union[str, Any]  ,				a		:		Optional[Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  model_inputs.pop('''candidate_labels'''    )
         __lowerCamelCase		=  model_inputs.pop('''text_inputs'''    )
         if isinstance(text_inputs[0]  ,				a    ):
             __lowerCamelCase		=  text_inputs[0]
         else:
             # Batching case.
             __lowerCamelCase		=  text_inputs[0][0]

         __lowerCamelCase		=  self.model(**a  ,				**a    )

         __lowerCamelCase		=  {
             '''candidate_labels''': candidate_labels,
             '''logits''': outputs.logits_per_image,
         }
         return model_outputs






     def    SCREAMING_SNAKE_CASE__   ( self		:		Dict  ,				a		:		Union[str, Any]    ):





         """simple docstring"""



         __lowerCamelCase		=  model_outputs.pop('''candidate_labels'''    )
         __lowerCamelCase		=  model_outputs['''logits'''][0]
         if self.framework == "pt":
             __lowerCamelCase		=  logits.softmax(dim=-1    ).squeeze(-1    )
             __lowerCamelCase		=  probs.tolist()
             if not isinstance(a  ,				a    ):
                 __lowerCamelCase		=  [scores]
         elif self.framework == "tf":
             __lowerCamelCase		=  stable_softmax(a  ,				axis=-1    )
             __lowerCamelCase		=  probs.numpy().tolist()
         else:
             raise ValueError(f"""Unsupported framework: {self.framework}"""    )

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





from typing import TYPE_CHECKING

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


A__								=						{
    '''configuration_ctrl''': ['''CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''CTRLConfig'''],
    '''tokenization_ctrl''': ['''CTRLTokenizer'''],
}

try:
				if not is_torch_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				A__								=						[
				    '''CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''',
				    '''CTRLForSequenceClassification''',
				    '''CTRLLMHeadModel''',
				    '''CTRLModel''',
				    '''CTRLPreTrainedModel''',
				]

try:
				if not is_tf_available():
								raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
				pass
else:
				A__								=						[
				    '''TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST''',
				    '''TFCTRLForSequenceClassification''',
				    '''TFCTRLLMHeadModel''',
				    '''TFCTRLModel''',
				    '''TFCTRLPreTrainedModel''',
				]


if TYPE_CHECKING:
				from .configuration_ctrl import CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP, CTRLConfig
				from .tokenization_ctrl import CTRLTokenizer

				try:
								if not is_torch_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_ctrl import (
								    CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
								    CTRLForSequenceClassification,
								    CTRLLMHeadModel,
								    CTRLModel,
								    CTRLPreTrainedModel,
								)

				try:
								if not is_tf_available():
												raise OptionalDependencyNotAvailable()
				except OptionalDependencyNotAvailable:
								pass
				else:
								from .modeling_tf_ctrl import (
								    TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
								    TFCTRLForSequenceClassification,
								    TFCTRLLMHeadModel,
								    TFCTRLModel,
								    TFCTRLPreTrainedModel,
								)

else:
				import sys

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

