

from collections import OrderedDict
from typing import Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


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

__lowercase     : Any       =						{
    '''microsoft/beit-base-patch16-224-pt22k''': (
        '''https://huggingface.co/microsoft/beit-base-patch16-224-pt22k/resolve/main/config.json'''
    ),
    # See all BEiT models at https://huggingface.co/models?filter=beit
}



class 						_A     (				__lowerCAmelCase				):





  '''simple docstring'''



  __lowerCamelCase			:      Optional[Any]					=   '''beit'''





  def __init__(  self   ,SCREAMING_SNAKE_CASE_=8192   ,SCREAMING_SNAKE_CASE_=768   ,SCREAMING_SNAKE_CASE_=12   ,SCREAMING_SNAKE_CASE_=12   ,SCREAMING_SNAKE_CASE_=3072   ,SCREAMING_SNAKE_CASE_="gelu"   ,SCREAMING_SNAKE_CASE_=0.0   ,SCREAMING_SNAKE_CASE_=0.0   ,SCREAMING_SNAKE_CASE_=0.02   ,SCREAMING_SNAKE_CASE_=1E-12   ,SCREAMING_SNAKE_CASE_=224   ,SCREAMING_SNAKE_CASE_=16   ,SCREAMING_SNAKE_CASE_=3   ,SCREAMING_SNAKE_CASE_=False   ,SCREAMING_SNAKE_CASE_=False   ,SCREAMING_SNAKE_CASE_=False   ,SCREAMING_SNAKE_CASE_=False   ,SCREAMING_SNAKE_CASE_=0.1   ,SCREAMING_SNAKE_CASE_=0.1   ,SCREAMING_SNAKE_CASE_=True   ,SCREAMING_SNAKE_CASE_=[3, 5, 7, 11]   ,SCREAMING_SNAKE_CASE_=[1, 2, 3, 6]   ,SCREAMING_SNAKE_CASE_=True   ,SCREAMING_SNAKE_CASE_=0.4   ,SCREAMING_SNAKE_CASE_=256   ,SCREAMING_SNAKE_CASE_=1   ,SCREAMING_SNAKE_CASE_=False   ,SCREAMING_SNAKE_CASE_=255   ,**SCREAMING_SNAKE_CASE_   ,):

      '''simple docstring'''
      super().__init__(**__SCREAMING_SNAKE_CASE    )

      snake_case							:		Dict        =		vocab_size
      snake_case							:		List[str]        =		hidden_size
      snake_case							:		Dict        =		num_hidden_layers
      snake_case							:		Tuple        =		num_attention_heads
      snake_case							:		List[Any]        =		intermediate_size
      snake_case							:		Any        =		hidden_act
      snake_case							:		Any        =		hidden_dropout_prob
      snake_case							:		Any        =		attention_probs_dropout_prob
      snake_case							:		Optional[Any]        =		initializer_range
      snake_case							:		Optional[Any]        =		layer_norm_eps

      snake_case							:		int        =		image_size
      snake_case							:		Dict        =		patch_size
      snake_case							:		str        =		num_channels
      snake_case							:		Optional[int]        =		use_mask_token
      snake_case							:		Tuple        =		use_absolute_position_embeddings
      snake_case							:		Optional[Any]        =		use_relative_position_bias
      snake_case							:		List[str]        =		use_shared_relative_position_bias
      snake_case							:		Any        =		layer_scale_init_value
      snake_case							:		Optional[int]        =		drop_path_rate
      snake_case							:		List[Any]        =		use_mean_pooling
      # decode head attributes (semantic segmentation)
      snake_case							:		Optional[int]        =		out_indices
      snake_case							:		Tuple        =		pool_scales
      # auxiliary head attributes (semantic segmentation)
      snake_case							:		List[Any]        =		use_auxiliary_head
      snake_case							:		Dict        =		auxiliary_loss_weight
      snake_case							:		Dict        =		auxiliary_channels
      snake_case							:		Optional[Any]        =		auxiliary_num_convs
      snake_case							:		Tuple        =		auxiliary_concat_input
      snake_case							:		List[str]        =		semantic_loss_ignore_index







class 						_A     (				__lowerCAmelCase				):





  '''simple docstring'''



  __lowerCamelCase			:      Optional[int]					=   version.parse('''1.11'''				)





  @property
  def    snake_case_       (  self    ):

      '''simple docstring'''
      return OrderedDict(
          [
              ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
          ]    )





  @property
  def    snake_case_       (  self    ):

      '''simple docstring'''
      return 1E-4









'''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_							:	str	     =		logging.get_logger(__name__)





@add_end_docstrings(__lowerCAmelCase)
class      lowerCAmelCase (			__lowerCAmelCase):


       def __init__( self     ,	**__SCREAMING_SNAKE_CASE	)   ->	Optional[int]:



            '''simple docstring'''




            super().__init__(**__SCREAMING_SNAKE_CASE	)

            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     ,	__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE	)   ->	List[Any]:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	**__SCREAMING_SNAKE_CASE	)   ->	Tuple:



            '''simple docstring'''




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

            return preprocess_params, {}, {}


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE     ,	__SCREAMING_SNAKE_CASE=None     ,	__SCREAMING_SNAKE_CASE="This is a photo of {}."	)   ->	Optional[Any]:



            '''simple docstring'''




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


       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	Dict:



            '''simple docstring'''




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

            __snake_case            =	self.model(**__SCREAMING_SNAKE_CASE     ,	**__SCREAMING_SNAKE_CASE	)

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




       def    lowerCAmelCase   ( self     ,	__SCREAMING_SNAKE_CASE	)   ->	str:



            '''simple docstring'''




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

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






