

"""simple docstring"""




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
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


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

A_				:      List[str]           =			{
    "microsoft/swin-tiny-patch4-window7-224": (
        "https://huggingface.co/microsoft/swin-tiny-patch4-window7-224/resolve/main/config.json"
    ),
    # See all Swin models at https://huggingface.co/models?filter=swin
}





class  lowerCamelCase    (a_      ,a_      ):
			lowerCamelCase__ :		Dict       		=				'''swin'''

			lowerCamelCase__ :		Union[str, Any]       		=				{
			    '''num_attention_heads''': '''num_heads''',
			    '''num_hidden_layers''': '''num_layers''',
			}

			def __init__(       self					:    int     ,					__UpperCAmelCase					:    Dict=2_2_4     ,					__UpperCAmelCase					:    Tuple=4     ,					__UpperCAmelCase					:    Optional[int]=3     ,					__UpperCAmelCase					:    List[Any]=9_6     ,					__UpperCAmelCase					:    str=[2, 2, 6, 2]     ,					__UpperCAmelCase					:    Union[str, Any]=[3, 6, 1_2, 2_4]     ,					__UpperCAmelCase					:    List[str]=7     ,					__UpperCAmelCase					:    Optional[Any]=4.0     ,					__UpperCAmelCase					:    Tuple=True     ,					__UpperCAmelCase					:    Optional[int]=0.0     ,					__UpperCAmelCase					:    Union[str, Any]=0.0     ,					__UpperCAmelCase					:    str=0.1     ,					__UpperCAmelCase					:    List[str]="gelu"     ,					__UpperCAmelCase					:    Any=False     ,					__UpperCAmelCase					:    Union[str, Any]=0.02     ,					__UpperCAmelCase					:    Union[str, Any]=1e-5     ,					__UpperCAmelCase					:    Optional[Any]=3_2     ,					__UpperCAmelCase					:    str=None     ,					__UpperCAmelCase					:    int=None     ,					**__UpperCAmelCase					:    Any     ,					) ->     int:
						super().__init__(**_SCREAMING_SNAKE_CASE							)

						SCREAMING_SNAKE_CASE__										=   image_size
						SCREAMING_SNAKE_CASE__										=   patch_size
						SCREAMING_SNAKE_CASE__										=   num_channels
						SCREAMING_SNAKE_CASE__										=   embed_dim
						SCREAMING_SNAKE_CASE__										=   depths
						SCREAMING_SNAKE_CASE__										=   len(_SCREAMING_SNAKE_CASE							)
						SCREAMING_SNAKE_CASE__										=   num_heads
						SCREAMING_SNAKE_CASE__										=   window_size
						SCREAMING_SNAKE_CASE__										=   mlp_ratio
						SCREAMING_SNAKE_CASE__										=   qkv_bias
						SCREAMING_SNAKE_CASE__										=   hidden_dropout_prob
						SCREAMING_SNAKE_CASE__										=   attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE__										=   drop_path_rate
						SCREAMING_SNAKE_CASE__										=   hidden_act
						SCREAMING_SNAKE_CASE__										=   use_absolute_embeddings
						SCREAMING_SNAKE_CASE__										=   layer_norm_eps
						SCREAMING_SNAKE_CASE__										=   initializer_range
						SCREAMING_SNAKE_CASE__										=   encoder_stride
						# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
						# this indicates the channel dimension after the last stage of the model
						SCREAMING_SNAKE_CASE__										=   int(embed_dim * 2 ** (len(_SCREAMING_SNAKE_CASE							) - 1)							)
						SCREAMING_SNAKE_CASE__										=   ["""stem"""] + [F"""stage{idx}""" for idx in range(1     ,					len(_SCREAMING_SNAKE_CASE							) + 1							)]
						SCREAMING_SNAKE_CASE__				,		SCREAMING_SNAKE_CASE__										=   get_aligned_output_features_output_indices(
						    out_features=_SCREAMING_SNAKE_CASE     ,					out_indices=_SCREAMING_SNAKE_CASE     ,					stage_names=self.stage_names							)





class  lowerCamelCase    (a_      ):
			lowerCamelCase__ :		Any       		=				version.parse('1.11'      )

			@property
			def        SCREAMING_SNAKE_CASE					(       self					:    Tuple							) ->     Tuple:
						return OrderedDict(
						    [
						        ("""pixel_values""", {0: """batch""", 1: """num_channels""", 2: """height""", 3: """width"""}),
						    ]							)





			@property
			def        SCREAMING_SNAKE_CASE					(       self					:    int							) ->     Dict:
						return 1e-4





'''simple docstring'''



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_tf_available():
     import tensorflow as tf

     from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
     from ..tf_utils import stable_softmax

if is_torch_available():
     from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING

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



@add_end_docstrings(a_			)
class 				_snake_case					(   a_			):

  def __init__(				self      , *_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      super().__init__(*_SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	)
      requires_backends(self      , 'vision'	)
      self.check_model_type(
          TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
          if self.framework == 'tf'
          else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING	)

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE=None	):





      '''simple docstring'''

      lowerCAmelCase 						=							{}
      if top_k is not None:
          lowerCAmelCase 						=							top_k
      return {}, {}, postprocess_params

  def __call__(				self      , _SCREAMING_SNAKE_CASE      , **_SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

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

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							load_image(_SCREAMING_SNAKE_CASE	)
      lowerCAmelCase 						=							self.image_processor(images=_SCREAMING_SNAKE_CASE      , return_tensors=self.framework	)
      return model_inputs

  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE	):





      '''simple docstring'''

      lowerCAmelCase 						=							self.model(**_SCREAMING_SNAKE_CASE	)
      return model_outputs


  def   _SCREAMING_SNAKE_CASE				(				self      , _SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE=5	):





      '''simple docstring'''

      if top_k > self.model.config.num_labels:
          lowerCAmelCase 						=							self.model.config.num_labels

      if self.framework == "pt":
          lowerCAmelCase 						=							model_outputs.logits.softmax(-1	)[0]
          lowerCAmelCase						,   lowerCAmelCase 						=							probs.topk(_SCREAMING_SNAKE_CASE	)
      elif self.framework == "tf":
          lowerCAmelCase 						=							stable_softmax(model_outputs.logits      , axis=-1	)[0]
          lowerCAmelCase 						=							tf.math.top_k(_SCREAMING_SNAKE_CASE      , k=_SCREAMING_SNAKE_CASE	)
          lowerCAmelCase						,   lowerCAmelCase 						=							topk.values.numpy(), topk.indices.numpy()
      else:
          raise ValueError(F'Unsupported framework: {self.framework}'	)

      lowerCAmelCase 						=							scores.tolist()
      lowerCAmelCase 						=							ids.tolist()
      return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(_SCREAMING_SNAKE_CASE      , _SCREAMING_SNAKE_CASE	)]





