




'''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 ..auto import CONFIG_MAPPING


_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE			=						{
    "microsoft/table-transformer-detection": (
        "https://huggingface.co/microsoft/table-transformer-detection/resolve/main/config.json"
    ),
}
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		"""table-transformer"""
					_UpperCamelCase							=		["""past_key_values"""]
					_UpperCamelCase							=		{
					    """hidden_size""": """d_model""",
					    """num_attention_heads""": """encoder_attention_heads""",
					}



					def __init__(	self     :						str      ,       _lowercase     :						Tuple=True      ,       _lowercase     :						List[str]=None      ,       _lowercase     :						Optional[Any]=3      ,       _lowercase     :						List[Any]=100      ,       _lowercase     :						Union[str, Any]=6      ,       _lowercase     :						Dict=2_048      ,       _lowercase     :						List[Any]=8      ,       _lowercase     :						str=6      ,       _lowercase     :						str=2_048      ,       _lowercase     :						Optional[Any]=8      ,       _lowercase     :						List[str]=0.0      ,       _lowercase     :						Tuple=0.0      ,       _lowercase     :						int=True      ,       _lowercase     :						Optional[int]="relu"      ,       _lowercase     :						str=256      ,       _lowercase     :						Optional[int]=0.1      ,       _lowercase     :						Dict=0.0      ,       _lowercase     :						List[str]=0.0      ,       _lowercase     :						Any=0.02      ,       _lowercase     :						Union[str, Any]=1.0      ,       _lowercase     :						Union[str, Any]=False      ,       _lowercase     :						str="sine"      ,       _lowercase     :						Any="resnet50"      ,       _lowercase     :						List[Any]=True      ,       _lowercase     :						Tuple=False      ,       _lowercase     :						Tuple=1      ,       _lowercase     :						List[str]=5      ,       _lowercase     :						Union[str, Any]=2      ,       _lowercase     :						Any=1      ,       _lowercase     :						Union[str, Any]=1      ,       _lowercase     :						Dict=5      ,       _lowercase     :						Optional[int]=2      ,       _lowercase     :						List[Any]=0.1      ,       **_lowercase     :						List[Any]      ,       )    ->							Optional[int]:
								if backbone_config is not None and use_timm_backbone:
											raise ValueError('You can\'t specify both `backbone_config` and `use_timm_backbone`.')

								if not use_timm_backbone:
											if backbone_config is None:
														logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.')
														A_									= CONFIG_MAPPING['resnet'](out_features=['stage4'])
											elif isinstance(_lowercase      ,       _lowercase):
														A_									= backbone_config.get('model_type')
														A_									= CONFIG_MAPPING[backbone_model_type]
														A_									= config_class.from_dict(_lowercase)
											# set timm attributes to None
											A_		, A_		, A_									= None, None, None

								A_									= use_timm_backbone
								A_									= backbone_config
								A_									= num_channels
								A_									= num_queries
								A_									= d_model
								A_									= encoder_ffn_dim
								A_									= encoder_layers
								A_									= encoder_attention_heads
								A_									= decoder_ffn_dim
								A_									= decoder_layers
								A_									= decoder_attention_heads
								A_									= dropout
								A_									= attention_dropout
								A_									= activation_dropout
								A_									= activation_function
								A_									= init_std
								A_									= init_xavier_std
								A_									= encoder_layerdrop
								A_									= decoder_layerdrop
								A_									= encoder_layers
								A_									= auxiliary_loss
								A_									= position_embedding_type
								A_									= backbone
								A_									= use_pretrained_backbone
								A_									= dilation
								# Hungarian matcher
								A_									= class_cost
								A_									= bbox_cost
								A_									= giou_cost
								# Loss coefficients
								A_									= mask_loss_coefficient
								A_									= dice_loss_coefficient
								A_									= bbox_loss_coefficient
								A_									= giou_loss_coefficient
								A_									= eos_coefficient
								super().__init__(is_encoder_decoder=_lowercase      ,       **_lowercase)



					@property
					def     __snake_case						(	self     :						Dict)    ->							int:
								return self.encoder_attention_heads



					@property
					def     __snake_case						(	self     :						Any)    ->							int:
								return self.d_model





class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					_UpperCamelCase							=		version.parse("""1.11"""				)



					@property
					def     __snake_case						(	self     :						Union[str, Any])    ->							Mapping[str, Mapping[int, str]]:
								return OrderedDict(
								    [
								        ('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
								        ('pixel_mask', {0: 'batch'}),
								    ])



					@property
					def     __snake_case						(	self     :						Optional[int])    ->							float:
								return 1E-5



					@property
					def     __snake_case						(	self     :						int)    ->							int:
								return 12










'''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

_SCREAMING_SNAKE_CASE			=						logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase				)
class   __UpperCAmelCase				(     lowerCAmelCase				):



					'''simple docstring'''





					def __init__(	self     :						int      ,       **_lowercase     :						List[Any])    ->							Union[str, Any]:
								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[Any]      ,       _lowercase     :						Union[str, List[str], "Image", List["Image"]]      ,       **_lowercase     :						List[Any])    ->							Any:
								return super().__call__(_lowercase      ,       **_lowercase)



					def     __snake_case						(	self     :						int      ,       **_lowercase     :						Union[str, Any])    ->							Any:
								A_									= {}
								if "candidate_labels" in kwargs:
											A_									= kwargs['candidate_labels']
								if "hypothesis_template" in kwargs:
											A_									= kwargs['hypothesis_template']

								return preprocess_params, {}, {}



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



					def     __snake_case						(	self     :						Optional[int]      ,       _lowercase     :						Tuple)    ->							Optional[int]:
								A_									= model_inputs.pop('candidate_labels')
								A_									= model_inputs.pop('text_inputs')
								if isinstance(text_inputs[0]      ,       _lowercase):
											A_									= text_inputs[0]
								else:
											# Batching case.
											A_									= text_inputs[0][0]

								A_									= self.model(**_lowercase      ,       **_lowercase)

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



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

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




