
'''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

__lowerCAmelCase   =       logging.get_logger(__name__)







@add_end_docstrings(UpperCamelCase__      )
class UpperCAmelCase__      (					UpperCamelCase__      ):





  """simple docstring"""

  def __init__(						self :	List[str]				,**_a :	Optional[int]			):


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


     '''simple docstring'''






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


  def     __lowercase						(						self :	Tuple				,**_a :	List[Any]			):


     '''simple docstring'''






     _a							:      Optional[Any]     =  {}
     if "candidate_labels" in kwargs:
        _a							:      int     =  kwargs['candidate_labels']
     if "hypothesis_template" in kwargs:
        _a							:      Union[str, Any]     =  kwargs['hypothesis_template']

     return preprocess_params, {}, {}


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


     '''simple docstring'''






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


  def     __lowercase						(						self :	str				,_a :	Dict			):


     '''simple docstring'''






     _a							:      Tuple     =  model_inputs.pop('candidate_labels'			)
     _a							:      str     =  model_inputs.pop('text_inputs'			)
     if isinstance(text_inputs[0]				,__A			):
        _a							:      str     =  text_inputs[0]
     else:
        # Batching case.
        _a							:      int     =  text_inputs[0][0]

     _a							:      List[Any]     =  self.model(**__A				,**__A			)

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


  def     __lowercase						(						self :	Dict				,_a :	Union[str, Any]			):


     '''simple docstring'''






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

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










import copy
from dataclasses import dataclass, field
from typing import ClassVar, Dict

from ..features import ClassLabel, Features, Value
from .base import TaskTemplate




@dataclass(frozen=UpperCamelCase__     )
class 	UpperCamelCase_							(  UpperCamelCase__     ):
							# `task` is not a ClassVar since we want it to be part of the `asdict` output for JSON serialization
							lowerCamelCase_							     =       field(default="text-classification"					,	metadata={"include_in_asdict_even_if_is_default": True}     )
							lowerCamelCase_							     =       Features({"text": Value("string"     )}     )
							lowerCamelCase_							     =       Features({"labels": ClassLabel}     )
							lowerCamelCase_							     =       "text"
							lowerCamelCase_							     =       "labels"


							def   _snake_case	(				self     :Any				,					__A     :Dict		) -> Optional[Any]:



									"""simple docstring"""



									if self.label_column not in features:
											raise ValueError(f'''Column {self.label_column} is not present in features.'''		)
									if not isinstance(features[self.label_column]				,					__A		):
											raise ValueError(f'''Column {self.label_column} is not a ClassLabel.'''		)
									SCREAMING_SNAKE_CASE__								=   copy.deepcopy(self		)
									SCREAMING_SNAKE_CASE__								=   self.label_schema.copy()
									SCREAMING_SNAKE_CASE__								=   features[self.label_column]
									SCREAMING_SNAKE_CASE__								=   label_schema
									return task_template


							@property
							def   _snake_case	(				self     :str		) -> Dict[str, str]:



									"""simple docstring"""



									return {
									    self.text_column: "text",
									    self.label_column: "labels",
									}