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(__A       )
class   snake_case_       (		__A       ):






   def __init__(      self				:     List[Any]	,						**lowercase_				:     Union[str, Any]  )					->						Tuple:
       super().__init__(**lowercase_  )

       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[int]	,						lowercase_				:     Union[str, List[str], "Image", List["Image"]]	,						**lowercase_				:     str  )					->						Optional[int]:
       return super().__call__(lowercase_	,						**lowercase_  )






   def       __UpperCamelCase     (      self				:     Any	,						**lowercase_				:     Tuple  )					->						Optional[Any]:
       lowercase__ :   List[Any]    					=				{}
       if "candidate_labels" in kwargs:
           lowercase__ :   int    					=				kwargs["candidate_labels"]
       if "hypothesis_template" in kwargs:
           lowercase__ :   Dict    					=				kwargs["hypothesis_template"]

       return preprocess_params, {}, {}






   def       __UpperCamelCase     (      self				:     str	,						lowercase_				:     List[Any]	,						lowercase_				:     Tuple=None	,						lowercase_				:     List[str]="This is a photo of {}."  )					->						Tuple:
       lowercase__ :   str    					=				load_image(lowercase_  )
       lowercase__ :   List[Any]    					=				self.image_processor(images=[image]	,						return_tensors=self.framework  )
       lowercase__ :   Optional[int]    					=				candidate_labels
       lowercase__ :   Optional[Any]    					=				[hypothesis_template.format(lowercase_  ) for x in candidate_labels]
       lowercase__ :   Union[str, Any]    					=				self.tokenizer(lowercase_	,						return_tensors=self.framework	,						padding=lowercase_  )
       lowercase__ :   int    					=				[text_inputs]
       return inputs






   def       __UpperCamelCase     (      self				:     Dict	,						lowercase_				:     List[Any]  )					->						Optional[int]:
       lowercase__ :   Tuple    					=				model_inputs.pop("candidate_labels"  )
       lowercase__ :   List[Any]    					=				model_inputs.pop("text_inputs"  )
       if isinstance(text_inputs[0]	,						lowercase_  ):
           lowercase__ :   List[str]    					=				text_inputs[0]
       else:
           # Batching case.
           lowercase__ :   Any    					=				text_inputs[0][0]

       lowercase__ :   List[str]    					=				self.model(**lowercase_	,						**lowercase_  )

       lowercase__ :   str    					=				{
           "candidate_labels": candidate_labels,
           "logits": outputs.logits_per_image,
       }
       return model_outputs







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

       lowercase__ :   Optional[Any]    					=				[
           {"score": score, "label": candidate_label}
           for score, candidate_label in sorted(zip(lowercase_	,						lowercase_  )	,						key=lambda lowercase_  : -x[0]  )
       ]
       return result







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


_A		       =						{
    'configuration_convbert': ['CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ConvBertConfig', 'ConvBertOnnxConfig'],
    'tokenization_convbert': ['ConvBertTokenizer'],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		       =						['ConvBertTokenizerFast']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		       =						[
       'CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
       'ConvBertForMaskedLM',
       'ConvBertForMultipleChoice',
       'ConvBertForQuestionAnswering',
       'ConvBertForSequenceClassification',
       'ConvBertForTokenClassification',
       'ConvBertLayer',
       'ConvBertModel',
       'ConvBertPreTrainedModel',
       'load_tf_weights_in_convbert',
   ]


try:
   if not is_tf_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   _A		       =						[
       'TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
       'TFConvBertForMaskedLM',
       'TFConvBertForMultipleChoice',
       'TFConvBertForQuestionAnswering',
       'TFConvBertForSequenceClassification',
       'TFConvBertForTokenClassification',
       'TFConvBertLayer',
       'TFConvBertModel',
       'TFConvBertPreTrainedModel',
   ]


if TYPE_CHECKING:
   from .configuration_convbert import CONVBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, ConvBertConfig, ConvBertOnnxConfig
   from .tokenization_convbert import ConvBertTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_convbert_fast import ConvBertTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_convbert import (
          CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          ConvBertForMaskedLM,
          ConvBertForMultipleChoice,
          ConvBertForQuestionAnswering,
          ConvBertForSequenceClassification,
          ConvBertForTokenClassification,
          ConvBertLayer,
          ConvBertModel,
          ConvBertPreTrainedModel,
          load_tf_weights_in_convbert,
      )

   try:
      if not is_tf_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_tf_convbert import (
          TF_CONVBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFConvBertForMaskedLM,
          TFConvBertForMultipleChoice,
          TFConvBertForQuestionAnswering,
          TFConvBertForSequenceClassification,
          TFConvBertForTokenClassification,
          TFConvBertLayer,
          TFConvBertModel,
          TFConvBertPreTrainedModel,
      )


else:
   import sys

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





