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

SCREAMING_SNAKE_CASE__		:       List[Any]       						=       logging.get_logger(__name__)

@add_end_docstrings(UpperCamelCase_    )
class    snake_case       (   UpperCamelCase_    ):




  def __init__(   self  :						List[str]  ,			**a_  :						Tuple					)->							List[str]:




       """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  :						Union[str, Any]  ,			a_  :						Union[str, List[str], "Image", List["Image"]]  ,			**a_  :						List[str]					)->							Optional[Any]:




       """simple docstring"""
       return super().__call__(a_  ,			**a_					)




  def 						__lowercase(   self  :						Dict  ,			**a_  :						str					)->							Dict:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					Dict      =		{}
       if "candidate_labels" in kwargs:
            SCREAMING_SNAKE_CASE__					:					Optional[int]      =		kwargs['candidate_labels']
       if "hypothesis_template" in kwargs:
            SCREAMING_SNAKE_CASE__					:					str      =		kwargs['hypothesis_template']

       return preprocess_params, {}, {}




  def 						__lowercase(   self  :						str  ,			a_  :						int  ,			a_  :						Optional[Any]=None  ,			a_  :						int="This is a photo of {}."					)->							Union[str, Any]:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					Tuple      =		load_image(a_					)
       SCREAMING_SNAKE_CASE__					:					Any      =		self.image_processor(images=[image]  ,			return_tensors=self.framework					)
       SCREAMING_SNAKE_CASE__					:					str      =		candidate_labels
       SCREAMING_SNAKE_CASE__					:					Any      =		[hypothesis_template.format(a_					) for x in candidate_labels]
       SCREAMING_SNAKE_CASE__					:					List[str]      =		self.tokenizer(a_  ,			return_tensors=self.framework  ,			padding=a_					)
       SCREAMING_SNAKE_CASE__					:					int      =		[text_inputs]
       return inputs




  def 						__lowercase(   self  :						Union[str, Any]  ,			a_  :						List[str]					)->							str:




       """simple docstring"""
       SCREAMING_SNAKE_CASE__					:					List[str]      =		model_inputs.pop('candidate_labels'					)
       SCREAMING_SNAKE_CASE__					:					Optional[int]      =		model_inputs.pop('text_inputs'					)
       if isinstance(text_inputs[0]  ,			a_					):
            SCREAMING_SNAKE_CASE__					:					Union[str, Any]      =		text_inputs[0]
       else:
            # Batching case.
            SCREAMING_SNAKE_CASE__					:					Optional[Any]      =		text_inputs[0][0]

       SCREAMING_SNAKE_CASE__					:					Any      =		self.model(**a_  ,			**a_					)

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




  def 						__lowercase(   self  :						Optional[int]  ,			a_  :						Optional[int]					)->							Union[str, Any]:




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

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





from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCamelCase_						:     Optional[int]	       =							logging.get_logger(__name__)




class   __lowercase						(						__snake_case       ):
	_A       =   "timm_backbone"






	def __init__(self				: Any      ,	snake_case				: List[Any]=None      ,	snake_case				: int=3      ,	snake_case				: Dict=True      ,	snake_case				: Union[str, Any]=True      ,	snake_case				: Any=None      ,	**snake_case				: int      ,	) ->			Optional[int]:
							super().__init__(**snake_case    )
							_lowercase       :	Dict           =   backbone
							_lowercase       :	Optional[Any]           =   num_channels
							_lowercase       :	Union[str, Any]           =   features_only
							_lowercase       :	Tuple           =   use_pretrained_backbone
							_lowercase       :	List[str]           =   True
							_lowercase       :	Tuple           =   out_indices if out_indices is not None else (-1,)




