




"""simple docstring"""





from typing import List, Union

import numpy as np

from ..tokenization_utils import TruncationStrategy
from ..utils import add_end_docstrings, logging
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, ChunkPipeline


A   =       logging.get_logger(__name__)



class      a__				(	__magic_name__   ):


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    List[str]):


						"""simple docstring"""




						if isinstance(UpperCamelCase_      ,  UpperCamelCase_):
									__UpperCAmelCase	: List[Any]		=					[label.strip() for label in labels.split(",") if label.strip()]
						return labels


			def __call__(      self      :    str      ,  UpperCamelCase_      :    Union[str, Any]      ,  UpperCamelCase_      :    Optional[Any]      ,  UpperCamelCase_      :    Optional[int]):


						"""simple docstring"""




						if len(UpperCamelCase_) == 0 or len(UpperCamelCase_) == 0:
									raise ValueError("You must include at least one label and at least one sequence.")
						if hypothesis_template.format(labels[0]) == hypothesis_template:
									raise ValueError(
									    (
									        "The provided hypothesis_template \"{}\" was not able to be formatted with the target labels. "
									        "Make sure the passed template includes formatting syntax such as {{}} where the label should go."
									    ).format(UpperCamelCase_))

						if isinstance(UpperCamelCase_      ,  UpperCamelCase_):
									__UpperCAmelCase	: Union[str, Any]		=					[sequences]

						__UpperCAmelCase	: Tuple		=					[]
						for sequence in sequences:
									sequence_pairs.extend([[sequence, hypothesis_template.format(UpperCamelCase_)] for label in labels])

						return sequence_pairs, sequences






@add_end_docstrings(__magic_name__   )
class      a__				(	__magic_name__   ):


			def __init__(      self      :    int      ,  UpperCamelCase_      :    Dict=ZeroShotClassificationArgumentHandler()      ,  *UpperCamelCase_      :    List[str]      ,  **UpperCamelCase_      :    List[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: List[Any]		=					args_parser
						super().__init__(*UpperCamelCase_      ,  **UpperCamelCase_)
						if self.entailment_id == -1:
									logger.warning(
									    "Failed to determine 'entailment' label id from the label2id mapping in the model config. Setting to "
									    "-1. Define a descriptive label2id mapping in the model config to ensure correct outputs.")


			@property
			def       a_     (      self      :    Tuple):


						"""simple docstring"""




						for label, ind in self.model.config.labelaid.items():
									if label.lower().startswith("entail"):
												return ind
						return -1


			def       a_     (      self      :    str      ,  UpperCamelCase_      :    Union[str, Any]      ,  UpperCamelCase_      :    List[Any]=True      ,  UpperCamelCase_      :    Any=True      ,  UpperCamelCase_      :    Tuple=TruncationStrategy.ONLY_FIRST      ,  **UpperCamelCase_      :    Optional[Any]):


						"""simple docstring"""




						__UpperCAmelCase	: List[str]		=					self.framework
						if self.tokenizer.pad_token is None:
									# Override for tokenizers not supporting padding
									logger.error(
									    "Tokenizer was not supporting padding necessary for zero-shot, attempting to use "
									    " `pad_token=eos_token`")
									__UpperCAmelCase	: List[str]		=					self.tokenizer.eos_token
						try:
									__UpperCAmelCase	: List[str]		=					self.tokenizer(
									    UpperCamelCase_      ,  add_special_tokens=UpperCamelCase_      ,  return_tensors=UpperCamelCase_      ,  padding=UpperCamelCase_      ,  truncation=UpperCamelCase_      ,  )
						except Exception as e:
									if "too short" in str(UpperCamelCase_):
												# tokenizers might yell that we want to truncate
												# to a value that is not even reached by the input.
												# In that case we don't want to truncate.
												# It seems there's not a really better way to catch that
												# exception.

												__UpperCAmelCase	: Any		=					self.tokenizer(
												    UpperCamelCase_      ,  add_special_tokens=UpperCamelCase_      ,  return_tensors=UpperCamelCase_      ,  padding=UpperCamelCase_      ,  truncation=TruncationStrategy.DO_NOT_TRUNCATE      ,  )
									else:
												raise e

						return inputs


			def       a_     (      self      :    Union[str, Any]      ,  **UpperCamelCase_      :    int):


						"""simple docstring"""




						if kwargs.get("multi_class"      ,  UpperCamelCase_) is not None:
									__UpperCAmelCase	: List[Any]		=					kwargs["multi_class"]
									logger.warning(
									    "The `multi_class` argument has been deprecated and renamed to `multi_label`. "
									    "`multi_class` will be removed in a future version of Transformers.")
						__UpperCAmelCase	: Dict		=					{}
						if "candidate_labels" in kwargs:
									__UpperCAmelCase	: List[str]		=					self._args_parser._parse_labels(kwargs["candidate_labels"])
						if "hypothesis_template" in kwargs:
									__UpperCAmelCase	: Any		=					kwargs["hypothesis_template"]

						__UpperCAmelCase	: Dict		=					{}
						if "multi_label" in kwargs:
									__UpperCAmelCase	: Optional[Any]		=					kwargs["multi_label"]
						return preprocess_params, {}, postprocess_params


			def __call__(      self      :    Tuple      ,  UpperCamelCase_      :    Union[str, List[str]]      ,  *UpperCamelCase_      :    Optional[Any]      ,  **UpperCamelCase_      :    List[Any]      ,  ):


						"""simple docstring"""




						if len(UpperCamelCase_) == 0:
									pass
						elif len(UpperCamelCase_) == 1 and "candidate_labels" not in kwargs:
									__UpperCAmelCase	: Union[str, Any]		=					args[0]
						else:
									raise ValueError(F"Unable to understand extra arguments {args}")

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


			def       a_     (      self      :    List[Any]      ,  UpperCamelCase_      :    Dict      ,  UpperCamelCase_      :    List[Any]=None      ,  UpperCamelCase_      :    int="This example is {}."):


						"""simple docstring"""




						__UpperCAmelCase	,     __UpperCAmelCase	: Optional[int]		=					self._args_parser(UpperCamelCase_      ,  UpperCamelCase_      ,  UpperCamelCase_)

						for i, (candidate_label, sequence_pair) in enumerate(zip(UpperCamelCase_      ,  UpperCamelCase_)):
									__UpperCAmelCase	: Union[str, Any]		=					self._parse_and_tokenize([sequence_pair])

									yield {
									    "candidate_label": candidate_label,
									    "sequence": sequences[0],
									    "is_last": i == len(UpperCamelCase_) - 1,
									    **model_input,
									}


			def       a_     (      self      :    Tuple      ,  UpperCamelCase_      :    List[str]):


						"""simple docstring"""




						__UpperCAmelCase	: List[str]		=					inputs["candidate_label"]
						__UpperCAmelCase	: Dict		=					inputs["sequence"]
						__UpperCAmelCase	: Tuple		=					{k: inputs[k] for k in self.tokenizer.model_input_names}
						__UpperCAmelCase	: Union[str, Any]		=					self.model(**UpperCamelCase_)

						__UpperCAmelCase	: Any		=					{
						    "candidate_label": candidate_label,
						    "sequence": sequence,
						    "is_last": inputs["is_last"],
						    **outputs,
						}
						return model_outputs


			def       a_     (      self      :    int      ,  UpperCamelCase_      :    int      ,  UpperCamelCase_      :    Optional[Any]=False):


						"""simple docstring"""




						__UpperCAmelCase	: Optional[Any]		=					[outputs["candidate_label"] for outputs in model_outputs]
						__UpperCAmelCase	: List[str]		=					[outputs["sequence"] for outputs in model_outputs]
						__UpperCAmelCase	: int		=					np.concatenate([output["logits"].numpy() for output in model_outputs])
						__UpperCAmelCase	: List[str]		=					logits.shape[0]
						__UpperCAmelCase	: List[Any]		=					len(UpperCamelCase_)
						__UpperCAmelCase	: Optional[int]		=					N // n
						__UpperCAmelCase	: Dict		=					logits.reshape((num_sequences, n, -1))

						if multi_label or len(UpperCamelCase_) == 1:
									# softmax over the entailment vs. contradiction dim for each label independently
									__UpperCAmelCase	: int		=					self.entailment_id
									__UpperCAmelCase	: Union[str, Any]		=					-1 if entailment_id == 0 else 0
									__UpperCAmelCase	: List[str]		=					reshaped_outputs[..., [contradiction_id, entailment_id]]
									__UpperCAmelCase	: Any		=					np.exp(UpperCamelCase_) / np.exp(UpperCamelCase_).sum(-1      ,  keepdims=UpperCamelCase_)
									__UpperCAmelCase	: Optional[int]		=					scores[..., 1]
						else:
									# softmax the "entailment" logits over all candidate labels
									__UpperCAmelCase	: Optional[Any]		=					reshaped_outputs[..., self.entailment_id]
									__UpperCAmelCase	: Optional[Any]		=					np.exp(UpperCamelCase_) / np.exp(UpperCamelCase_).sum(-1      ,  keepdims=UpperCamelCase_)

						__UpperCAmelCase	: str		=					list(reversed(scores[0].argsort()))
						return {
						    "sequence": sequences[0],
						    "labels": [candidate_labels[i] for i in top_inds],
						    "scores": scores[0, top_inds].tolist(),
						}








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


A   =       logging.get_logger(__name__)

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



class      a__				(	__magic_name__   ):
			lowercase_    =	"table-transformer"
			lowercase_    =	["past_key_values"]
			lowercase_    =	{
			    "hidden_size": "d_model",
			    "num_attention_heads": "encoder_attention_heads",
			}


			def __init__(      self      :    List[Any]      ,  UpperCamelCase_      :    int=True      ,  UpperCamelCase_      :    Tuple=None      ,  UpperCamelCase_      :    Optional[int]=3      ,  UpperCamelCase_      :    Any=100      ,  UpperCamelCase_      :    Dict=6      ,  UpperCamelCase_      :    List[str]=2048      ,  UpperCamelCase_      :    str=8      ,  UpperCamelCase_      :    Any=6      ,  UpperCamelCase_      :    Dict=2048      ,  UpperCamelCase_      :    str=8      ,  UpperCamelCase_      :    Any=0.0      ,  UpperCamelCase_      :    str=0.0      ,  UpperCamelCase_      :    Union[str, Any]=True      ,  UpperCamelCase_      :    Optional[int]="relu"      ,  UpperCamelCase_      :    str=256      ,  UpperCamelCase_      :    str=0.1      ,  UpperCamelCase_      :    Tuple=0.0      ,  UpperCamelCase_      :    Dict=0.0      ,  UpperCamelCase_      :    Dict=0.02      ,  UpperCamelCase_      :    Optional[Any]=1.0      ,  UpperCamelCase_      :    Optional[int]=False      ,  UpperCamelCase_      :    int="sine"      ,  UpperCamelCase_      :    Optional[Any]="resnet50"      ,  UpperCamelCase_      :    List[str]=True      ,  UpperCamelCase_      :    int=False      ,  UpperCamelCase_      :    Tuple=1      ,  UpperCamelCase_      :    Any=5      ,  UpperCamelCase_      :    Optional[Any]=2      ,  UpperCamelCase_      :    int=1      ,  UpperCamelCase_      :    List[str]=1      ,  UpperCamelCase_      :    List[str]=5      ,  UpperCamelCase_      :    Union[str, Any]=2      ,  UpperCamelCase_      :    Optional[int]=0.1      ,  **UpperCamelCase_      :    int      ,  ):


						"""simple docstring"""




						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.")
												__UpperCAmelCase	: int		=					CONFIG_MAPPING["resnet"](out_features=["stage4"])
									elif isinstance(UpperCamelCase_      ,  UpperCamelCase_):
												__UpperCAmelCase	: List[Any]		=					backbone_config.get("model_type")
												__UpperCAmelCase	: List[Any]		=					CONFIG_MAPPING[backbone_model_type]
												__UpperCAmelCase	: Optional[int]		=					config_class.from_dict(UpperCamelCase_)
									# set timm attributes to None
									__UpperCAmelCase	,     __UpperCAmelCase	,     __UpperCAmelCase	: List[Any]		=					None, None, None

						__UpperCAmelCase	: str		=					use_timm_backbone
						__UpperCAmelCase	: int		=					backbone_config
						__UpperCAmelCase	: Dict		=					num_channels
						__UpperCAmelCase	: Optional[Any]		=					num_queries
						__UpperCAmelCase	: List[Any]		=					d_model
						__UpperCAmelCase	: Union[str, Any]		=					encoder_ffn_dim
						__UpperCAmelCase	: int		=					encoder_layers
						__UpperCAmelCase	: Union[str, Any]		=					encoder_attention_heads
						__UpperCAmelCase	: str		=					decoder_ffn_dim
						__UpperCAmelCase	: Any		=					decoder_layers
						__UpperCAmelCase	: Dict		=					decoder_attention_heads
						__UpperCAmelCase	: List[Any]		=					dropout
						__UpperCAmelCase	: int		=					attention_dropout
						__UpperCAmelCase	: str		=					activation_dropout
						__UpperCAmelCase	: Union[str, Any]		=					activation_function
						__UpperCAmelCase	: Optional[int]		=					init_std
						__UpperCAmelCase	: Dict		=					init_xavier_std
						__UpperCAmelCase	: Tuple		=					encoder_layerdrop
						__UpperCAmelCase	: Any		=					decoder_layerdrop
						__UpperCAmelCase	: Tuple		=					encoder_layers
						__UpperCAmelCase	: Optional[int]		=					auxiliary_loss
						__UpperCAmelCase	: List[str]		=					position_embedding_type
						__UpperCAmelCase	: List[str]		=					backbone
						__UpperCAmelCase	: Optional[int]		=					use_pretrained_backbone
						__UpperCAmelCase	: Union[str, Any]		=					dilation
						# Hungarian matcher
						__UpperCAmelCase	: List[Any]		=					class_cost
						__UpperCAmelCase	: Tuple		=					bbox_cost
						__UpperCAmelCase	: int		=					giou_cost
						# Loss coefficients
						__UpperCAmelCase	: Any		=					mask_loss_coefficient
						__UpperCAmelCase	: Optional[Any]		=					dice_loss_coefficient
						__UpperCAmelCase	: Any		=					bbox_loss_coefficient
						__UpperCAmelCase	: int		=					giou_loss_coefficient
						__UpperCAmelCase	: List[Any]		=					eos_coefficient
						super().__init__(is_encoder_decoder=UpperCamelCase_      ,  **UpperCamelCase_)


			@property
			def       a_     (      self      :    int):


						"""simple docstring"""




						return self.encoder_attention_heads


			@property
			def       a_     (      self      :    int):


						"""simple docstring"""




						return self.d_model






class      a__				(	__magic_name__   ):
			lowercase_    =	version.parse("1.11"   )


			@property
			def       a_     (      self      :    Union[str, Any]):


						"""simple docstring"""




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


			@property
			def       a_     (      self      :    int):


						"""simple docstring"""




						return 1e-5


			@property
			def       a_     (      self      :    Tuple):


						"""simple docstring"""




						return 12


