




'''simple docstring'''







from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


A									=logging.get_logger(__name__)

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


class     _a						(			UpperCamelCase__							,							UpperCamelCase__				):
       __a       :  Tuple            =      """dinat"""

       __a       :  Union[str, Any]            =      {
           """num_attention_heads""": """num_heads""",
           """num_hidden_layers""": """num_layers""",
       }
       def __init__(			self		:			Dict     ,       lowercase		:			Tuple=4     ,       lowercase		:			str=3     ,       lowercase		:			str=64     ,       lowercase		:			Optional[Any]=[3, 4, 6, 5]     ,       lowercase		:			str=[2, 4, 8, 16]     ,       lowercase		:			Dict=7     ,       lowercase		:			Dict=[[1, 8, 1], [1, 4, 1, 4], [1, 2, 1, 2, 1, 2], [1, 1, 1, 1, 1]]     ,       lowercase		:			str=3.0     ,       lowercase		:			Optional[Any]=True     ,       lowercase		:			Dict=0.0     ,       lowercase		:			Optional[Any]=0.0     ,       lowercase		:			Union[str, Any]=0.1     ,       lowercase		:			List[str]="gelu"     ,       lowercase		:			str=0.02     ,       lowercase		:			Tuple=1E-5     ,       lowercase		:			Any=0.0     ,       lowercase		:			Union[str, Any]=None     ,       lowercase		:			Tuple=None     ,       **lowercase		:			Union[str, Any]     ,       ):



           '''simple docstring'''

           super().__init__(**_a       )

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






'''simple docstring'''







from typing import Union

from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging
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_VISUAL_QUESTION_ANSWERING_MAPPING

A									=logging.get_logger(__name__)


@add_end_docstrings(__a				)
class     _a						(			__a				):
       def __init__(			self		:			Optional[int]     ,       *lowercase		:			Any     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           super().__init__(*lowercase     ,       **lowercase       )
           self.check_model_type(lowercase       )
       def 					A   (			self		:			List[str]     ,       lowercase		:			str=None     ,       lowercase		:			List[str]=None     ,       lowercase		:			List[str]=None     ,       **lowercase		:			List[str]       ):



           '''simple docstring'''

           UpperCAmelCase ,  UpperCAmelCase     =	{}, {}
           if padding is not None:
               UpperCAmelCase     =	padding
           if truncation is not None:
               UpperCAmelCase     =	truncation
           if top_k is not None:
               UpperCAmelCase     =	top_k
           return preprocess_params, {}, postprocess_params
       def __call__(			self		:			Optional[Any]     ,       lowercase		:			Union["Image.Image", str]     ,       lowercase		:			str = None     ,       **lowercase		:			Optional[int]       ):



           '''simple docstring'''

           if isinstance(lowercase     ,       (Image.Image, str)       ) and isinstance(lowercase     ,       lowercase       ):
               UpperCAmelCase     =	{'''image''': image, '''question''': question}
           else:
               UpperCAmelCase     =	image
           UpperCAmelCase     =	super().__call__(lowercase     ,       **lowercase       )
           return results
       def 					A   (			self		:			List[Any]     ,       lowercase		:			List[str]     ,       lowercase		:			Any=False     ,       lowercase		:			Any=False       ):



           '''simple docstring'''

           UpperCAmelCase     =	load_image(inputs['''image''']       )
           UpperCAmelCase     =	self.tokenizer(
               inputs['''question''']     ,       return_tensors=self.framework     ,       padding=lowercase     ,       truncation=lowercase       )
           UpperCAmelCase     =	self.image_processor(images=lowercase     ,       return_tensors=self.framework       )
           model_inputs.update(lowercase       )
           return model_inputs
       def 					A   (			self		:			Dict     ,       lowercase		:			Optional[Any]       ):



           '''simple docstring'''

           UpperCAmelCase     =	self.model(**lowercase       )
           return model_outputs







       def 					A   (			self		:			Union[str, Any]     ,       lowercase		:			int     ,       lowercase		:			Optional[Any]=5       ):



           '''simple docstring'''

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

           if self.framework == "pt":
               UpperCAmelCase     =	model_outputs.logits.sigmoid()[0]
               UpperCAmelCase ,  UpperCAmelCase     =	probs.topk(lowercase       )
           else:
               raise ValueError(f"Unsupported framework: {self.framework}"       )

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




