





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__    ):


							def __init__(							self    :Union[str, Any]							,				**__A    :Dict		)   ->   Tuple:



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



									"""simple docstring"""



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


							def      _snake_case  (							self    :Optional[int]							,				**__A    :List[Any]		)   ->   List[Any]:



									"""simple docstring"""



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

									return preprocess_params, {}, {}


							def      _snake_case  (							self    :int							,				__A    :Any							,				__A    :List[str]=None							,				__A    :Any="This is a photo of {}."		)   ->   List[Any]:



									"""simple docstring"""



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


							def      _snake_case  (							self    :str							,				__A    :Optional[int]		)   ->   Union[str, Any]:



									"""simple docstring"""



									SCREAMING_SNAKE_CASE__			=      model_inputs.pop("""candidate_labels"""		)
									SCREAMING_SNAKE_CASE__			=      model_inputs.pop("""text_inputs"""		)
									if isinstance(text_inputs[0]							,				__A		):
											SCREAMING_SNAKE_CASE__			=      text_inputs[0]
									else:
											# Batching case.
											SCREAMING_SNAKE_CASE__			=      text_inputs[0][0]

									SCREAMING_SNAKE_CASE__			=      self.model(**__A							,				**__A		)

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


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



									"""simple docstring"""



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

									SCREAMING_SNAKE_CASE__			=      [
									    {"""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
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_lowerCamelCase   				=			logging.get_logger(__name__)

_lowerCamelCase   				=			{
    'shi-labs/nat-mini-in1k-224': 'https://huggingface.co/shi-labs/nat-mini-in1k-224/resolve/main/config.json',
    # See all Nat models at https://huggingface.co/models?filter=nat
}




class   UpperCamelCase_       (     UpperCamelCase__				,  UpperCamelCase__    ):
							lowerCamelCase_           =					"nat"

							lowerCamelCase_           =					{
							    "num_attention_heads": "num_heads",
							    "num_hidden_layers": "num_layers",
							}


							def __init__(							self    :List[Any]							,				__A    :Optional[Any]=4							,				__A    :Any=3							,				__A    :Optional[int]=64							,				__A    :Optional[int]=[3, 4, 6, 5]							,				__A    :Union[str, Any]=[2, 4, 8, 16]							,				__A    :Optional[Any]=7							,				__A    :Optional[Any]=3.0							,				__A    :List[Any]=True							,				__A    :int=0.0							,				__A    :Dict=0.0							,				__A    :Optional[Any]=0.1							,				__A    :str="gelu"							,				__A    :Optional[Any]=0.0_2							,				__A    :Optional[int]=1E-5							,				__A    :Optional[int]=0.0							,				__A    :Optional[Any]=None							,				__A    :Union[str, Any]=None							,				**__A    :Union[str, Any]							,				)   ->   Optional[int]:



									"""simple docstring"""



									super().__init__(**__A		)

									SCREAMING_SNAKE_CASE__			=      patch_size
									SCREAMING_SNAKE_CASE__			=      num_channels
									SCREAMING_SNAKE_CASE__			=      embed_dim
									SCREAMING_SNAKE_CASE__			=      depths
									SCREAMING_SNAKE_CASE__			=      len(__A		)
									SCREAMING_SNAKE_CASE__			=      num_heads
									SCREAMING_SNAKE_CASE__			=      kernel_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__			=      layer_norm_eps
									SCREAMING_SNAKE_CASE__			=      initializer_range
									# we set the hidden_size attribute in order to make Nat work with VisionEncoderDecoderModel
									# this indicates the channel dimension after the last stage of the model
									SCREAMING_SNAKE_CASE__			=      int(embed_dim * 2 ** (len(__A		) - 1)		)
									SCREAMING_SNAKE_CASE__			=      layer_scale_init_value
									SCREAMING_SNAKE_CASE__			=      ["""stem"""] + [f'''stage{idx}''' for idx in range(1							,				len(__A		) + 1		)]
									SCREAMING_SNAKE_CASE__	,						SCREAMING_SNAKE_CASE__			=      get_aligned_output_features_output_indices(
									    out_features=__A							,				out_indices=__A							,				stage_names=self.stage_names		)