





from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


__lowercase							:int							=	logging.get_logger(__name__)

# General docstring
__lowercase							:str							=	"ResNetConfig"

# Base docstring
__lowercase							:Optional[Any]							=	"microsoft/resnet-50"
__lowercase							:Optional[Any]							=	[1, 2_048, 7, 7]

# Image classification docstring
__lowercase							:Optional[int]							=	"microsoft/resnet-50"
__lowercase							:Optional[int]							=	"tiger cat"

__lowercase							:Tuple							=	[
    "microsoft/resnet-50",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]



class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  Dict				,						a					:  int				,						a					:  int = 3				,						a					:  int = 1				,						a					:  str = "relu"				,						**a					:  str     )						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       kernel_size // 2
													SCREAMING_SNAKE_CASE__  :					Any =       tf.keras.layers.ConvaD(
													    a				,						kernel_size=a				,						strides=a				,						padding="valid"				,						use_bias=a				,						name="convolution"     )
													# Use same default momentum and epsilon as PyTorch equivalent
													SCREAMING_SNAKE_CASE__  :					Any =       tf.keras.layers.BatchNormalization(epsilon=1E-5				,						momentum=0.9				,						name="normalization"     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("linear"     )

							def   A_	(   self					:  Optional[Any]				,						a					:  tf.Tensor     )						->tf.Tensor:
													# Pad to match that done in the PyTorch Conv2D model
													SCREAMING_SNAKE_CASE__  :					Dict =       (self.pad_value, self.pad_value)
													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       tf.pad(a				,						[(0, 0), height_pad, width_pad, (0, 0)]     )
													SCREAMING_SNAKE_CASE__  :					int =       self.conv(a     )
													return hidden_state






							def   A_	(   self					:  Optional[Any]				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__  :					List[str] =       self.convolution(a     )
													SCREAMING_SNAKE_CASE__  :					Any =       self.normalization(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					int =       self.activation(a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  Union[str, Any]				,						a					:  ResNetConfig				,						**a					:  Optional[int]     )						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       TFResNetConvLayer(
													    config.embedding_size				,						kernel_size=7				,						stride=2				,						activation=config.hidden_act				,						name="embedder"				,						)
													SCREAMING_SNAKE_CASE__  :					Tuple =       tf.keras.layers.MaxPoolaD(pool_size=3				,						strides=2				,						padding="valid"				,						name="pooler"     )
													SCREAMING_SNAKE_CASE__  :					Any =       config.num_channels






							def   A_	(   self					:  Tuple				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__  :					str =       shape_list(a     )
													if tf.executing_eagerly() and num_channels != self.num_channels:
																			raise ValueError(
																			    "Make sure that the channel dimension of the pixel values match with the one set in the configuration."     )
													SCREAMING_SNAKE_CASE__  :					List[Any] =       pixel_values
													SCREAMING_SNAKE_CASE__  :					List[Any] =       self.embedder(a     )
													SCREAMING_SNAKE_CASE__  :					Any =       tf.pad(a				,						[[0, 0], [1, 1], [1, 1], [0, 0]]     )
													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       self.pooler(a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  List[Any]				,						a					:  int				,						a					:  int = 2				,						**a					:  Union[str, Any]     )						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       tf.keras.layers.ConvaD(
													    a				,						kernel_size=1				,						strides=a				,						use_bias=a				,						name="convolution"     )
													# Use same default momentum and epsilon as PyTorch equivalent
													SCREAMING_SNAKE_CASE__  :					Dict =       tf.keras.layers.BatchNormalization(epsilon=1E-5				,						momentum=0.9				,						name="normalization"     )






							def   A_	(   self					:  Union[str, Any]				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__  :					str =       x
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       self.convolution(a     )
													SCREAMING_SNAKE_CASE__  :					int =       self.normalization(a				,						training=a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  int				,						a					:  int				,						a					:  int				,						a					:  int = 1				,						a					:  str = "relu"				,						**a					:  str     )						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       in_channels != out_channels or stride != 1
													SCREAMING_SNAKE_CASE__  :					Dict =       TFResNetConvLayer(a				,						stride=a				,						name="layer.0"     )
													SCREAMING_SNAKE_CASE__  :					Any =       TFResNetConvLayer(a				,						activation=a				,						name="layer.1"     )
													SCREAMING_SNAKE_CASE__  :					Tuple =       (
													    TFResNetShortCut(a				,						stride=a				,						name="shortcut"     )
													    if should_apply_shortcut
													    else tf.keras.layers.Activation("linear"				,						name="shortcut"     )
													)
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       ACTaFN[activation]






							def   A_	(   self					:  List[Any]				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__  :					List[Any] =       hidden_state
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.conva(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       self.conva(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					Dict =       self.shortcut(a				,						training=a     )
													hidden_state += residual
													SCREAMING_SNAKE_CASE__  :					int =       self.activation(a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  List[str]				,						a					:  int				,						a					:  int				,						a					:  int = 1				,						a					:  str = "relu"				,						a					:  int = 4				,						**a					:  List[Any]				,						)						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					Any =       in_channels != out_channels or stride != 1
													SCREAMING_SNAKE_CASE__  :					Dict =       out_channels // reduction
													SCREAMING_SNAKE_CASE__  :					Dict =       TFResNetConvLayer(a				,						kernel_size=1				,						name="layer.0"     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       TFResNetConvLayer(a				,						stride=a				,						name="layer.1"     )
													SCREAMING_SNAKE_CASE__  :					Tuple =       TFResNetConvLayer(a				,						kernel_size=1				,						activation=a				,						name="layer.2"     )
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       (
													    TFResNetShortCut(a				,						stride=a				,						name="shortcut"     )
													    if should_apply_shortcut
													    else tf.keras.layers.Activation("linear"				,						name="shortcut"     )
													)
													SCREAMING_SNAKE_CASE__  :					str =       ACTaFN[activation]






							def   A_	(   self					:  Optional[int]				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__  :					List[str] =       hidden_state
													SCREAMING_SNAKE_CASE__  :					List[Any] =       self.conva(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       self.conva(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					Any =       self.conva(a				,						training=a     )
													SCREAMING_SNAKE_CASE__  :					int =       self.shortcut(a				,						training=a     )
													hidden_state += residual
													SCREAMING_SNAKE_CASE__  :					List[Any] =       self.activation(a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  Dict				,						a					:  ResNetConfig				,						a					:  int				,						a					:  int				,						a					:  int = 2				,						a					:  int = 2				,						**a					:  Optional[int]     )						->None:
													super().__init__(**a     )

													SCREAMING_SNAKE_CASE__  :					List[str] =       TFResNetBottleNeckLayer if config.layer_type == "bottleneck" else TFResNetBasicLayer

													SCREAMING_SNAKE_CASE__  :					Optional[int] =       [layer(a				,						a				,						stride=a				,						activation=config.hidden_act				,						name="layers.0"     )]
													layers += [
													    layer(a				,						a				,						activation=config.hidden_act				,						name=f"""layers.{i + 1}"""     )
													    for i in range(depth - 1     )
													]
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       layers






							def   A_	(   self					:  List[str]				,						a					:  tf.Tensor				,						a					:  bool = False     )						->tf.Tensor:
													for layer in self.stage_layers:
																			SCREAMING_SNAKE_CASE__  :					str =       layer(a				,						training=a     )
													return hidden_state







class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							def __init__(   self					:  Optional[Any]				,						a					:  ResNetConfig				,						**a					:  str     )						->None:
													super().__init__(**a     )
													# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       [
													    TFResNetStage(
													        a				,						config.embedding_size				,						config.hidden_sizes[0]				,						stride=2 if config.downsample_in_first_stage else 1				,						depth=config.depths[0]				,						name="stages.0"				,						)
													]
													for i, (in_channels, out_channels, depth) in enumerate(
													    zip(config.hidden_sizes				,						config.hidden_sizes[1:]				,						config.depths[1:]     )     ):
																			self.stages.append(TFResNetStage(a				,						a				,						a				,						depth=a				,						name=f"""stages.{i + 1}"""     )     )






							def   A_	(   self					:  List[Any]				,						a					:  tf.Tensor				,						a					:  bool = False				,						a					:  bool = True				,						a					:  bool = False				,						)						->TFBaseModelOutputWithNoAttention:
													SCREAMING_SNAKE_CASE__  :					int =       () if output_hidden_states else None

													for stage_module in self.stages:
																			if output_hidden_states:
																									SCREAMING_SNAKE_CASE__  :					int =       hidden_states + (hidden_state,)

																			SCREAMING_SNAKE_CASE__  :					Any =       stage_module(a				,						training=a     )

													if output_hidden_states:
																			SCREAMING_SNAKE_CASE__  :					str =       hidden_states + (hidden_state,)

													if not return_dict:
																			return tuple(v for v in [hidden_state, hidden_states] if v is not None     )

													return TFBaseModelOutputWithNoAttention(last_hidden_state=a				,						hidden_states=a     )







class  _a  (					lowercase__				):






							"""simple docstring"""

							snake_case_							=    ResNetConfig
							snake_case_							=    "resnet"
							snake_case_							=    "pixel_values"

							@property
							def   A_	(   self					:  List[str]     )						->Any:
													return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)				,						dtype=tf.floataa     )}







__lowercase							:Union[str, Any]							=	R"\n    This model is a TensorFlow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n"


__lowercase							:Optional[Any]							=	R"\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"



@keras_serializable
class  _a  (					tf.keras.layers.Layer				):






							"""simple docstring"""

							snake_case_							=    ResNetConfig

							def __init__(   self					:  List[Any]				,						a					:  ResNetConfig				,						**a					:  str     )						->None:
													super().__init__(**a     )
													SCREAMING_SNAKE_CASE__  :					List[Any] =       config
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       TFResNetEmbeddings(a				,						name="embedder"     )
													SCREAMING_SNAKE_CASE__  :					Any =       TFResNetEncoder(a				,						name="encoder"     )
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       tf.keras.layers.GlobalAveragePoolingaD(keepdims=a     )






							@unpack_inputs
							def   A_	(   self					:  Any				,						a					:  tf.Tensor				,						a					:  Optional[bool] = None				,						a					:  Optional[bool] = None				,						a					:  bool = False				,						)						->Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
													SCREAMING_SNAKE_CASE__  :					Tuple =       (
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)
													SCREAMING_SNAKE_CASE__  :					Dict =       return_dict if return_dict is not None else self.config.use_return_dict

													# TF 2.0 image layers can't use NCHW format when running on CPU.
													# We transpose to NHWC format and then transpose back after the full forward pass.
													# (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
													SCREAMING_SNAKE_CASE__  :					Dict =       tf.transpose(a				,						perm=[0, 2, 3, 1]     )
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.embedder(a				,						training=a     )

													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       self.encoder(
													    a				,						output_hidden_states=a				,						return_dict=a				,						training=a     )

													SCREAMING_SNAKE_CASE__  :					List[Any] =       encoder_outputs[0]

													SCREAMING_SNAKE_CASE__  :					str =       self.pooler(a     )

													# Transpose all the outputs to the NCHW format
													# (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
													SCREAMING_SNAKE_CASE__  :					Any =       tf.transpose(a				,						(0, 3, 1, 2)     )
													SCREAMING_SNAKE_CASE__  :					Dict =       tf.transpose(a				,						(0, 3, 1, 2)     )
													SCREAMING_SNAKE_CASE__  :					Any =       ()
													for hidden_state in encoder_outputs[1:]:
																			SCREAMING_SNAKE_CASE__  :					Dict =       hidden_states + tuple(tf.transpose(a				,						(0, 3, 1, 2)     ) for h in hidden_state     )

													if not return_dict:
																			return (last_hidden_state, pooled_output) + hidden_states

													SCREAMING_SNAKE_CASE__  :					Tuple =       hidden_states if output_hidden_states else None

													return TFBaseModelOutputWithPoolingAndNoAttention(
													    last_hidden_state=a				,						pooler_output=a				,						hidden_states=a				,						)







@add_start_docstrings(
    "The bare ResNet model outputting raw features without any specific head on top."       ,				lowercase__       ,				)
class  _a  (					lowercase__				):






							"""simple docstring"""

							def __init__(   self					:  Optional[int]				,						a					:  ResNetConfig				,						**a					:  Union[str, Any]     )						->None:
													super().__init__(a				,						**a     )
													SCREAMING_SNAKE_CASE__  :					int =       TFResNetMainLayer(config=a				,						name="resnet"     )






							@add_start_docstrings_to_model_forward(a     )
							@add_code_sample_docstrings(
							    checkpoint=_CHECKPOINT_FOR_DOC				,						output_type=a				,						config_class=_CONFIG_FOR_DOC				,						modality="vision"				,						expected_output=_EXPECTED_OUTPUT_SHAPE				,						)
							@unpack_inputs
							def   A_	(   self					:  Union[str, Any]				,						a					:  tf.Tensor				,						a					:  Optional[bool] = None				,						a					:  Optional[bool] = None				,						a					:  bool = False				,						)						->Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
													SCREAMING_SNAKE_CASE__  :					Tuple =       (
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)
													SCREAMING_SNAKE_CASE__  :					List[str] =       return_dict if return_dict is not None else self.config.use_return_dict

													SCREAMING_SNAKE_CASE__  :					Tuple =       self.resnet(
													    pixel_values=a				,						output_hidden_states=a				,						return_dict=a				,						training=a				,						)
													return resnet_outputs







@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "       ,				lowercase__       ,				)
class  _a  (					lowercase__       ,				lowercase__				):






							"""simple docstring"""

							def __init__(   self					:  Optional[int]				,						a					:  ResNetConfig				,						**a					:  int     )						->None:
													super().__init__(a				,						**a     )
													SCREAMING_SNAKE_CASE__  :					List[str] =       config.num_labels
													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       TFResNetMainLayer(a				,						name="resnet"     )
													# classification head
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       (
													    tf.keras.layers.Dense(config.num_labels				,						name="classifier.1"     )
													    if config.num_labels > 0
													    else tf.keras.layers.Activation("linear"				,						name="classifier.1"     )
													)

							def   A_	(   self					:  str				,						a					:  tf.Tensor     )						->tf.Tensor:
													SCREAMING_SNAKE_CASE__  :					List[Any] =       tf.keras.layers.Flatten()(a     )
													SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.classifier_layer(a     )
													return logits






							@add_start_docstrings_to_model_forward(a     )
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT				,						output_type=a				,						config_class=_CONFIG_FOR_DOC				,						expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT				,						)
							@unpack_inputs
							def   A_	(   self					:  Optional[int]				,						a					:  tf.Tensor = None				,						a					:  tf.Tensor = None				,						a					:  bool = None				,						a					:  bool = None				,						a					:  bool = False				,						)						->Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:
													SCREAMING_SNAKE_CASE__  :					int =       return_dict if return_dict is not None else self.config.use_return_dict

													SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.resnet(
													    a				,						output_hidden_states=a				,						return_dict=a				,						training=a     )

													SCREAMING_SNAKE_CASE__  :					List[str] =       outputs.pooler_output if return_dict else outputs[1]

													SCREAMING_SNAKE_CASE__  :					Dict =       self.classifier(a     )

													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       None if labels is None else self.hf_compute_loss(a				,						a     )

													if not return_dict:
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       (logits,) + outputs[2:]
																			return (loss,) + output if loss is not None else output

													return TFImageClassifierOutputWithNoAttention(loss=a				,						logits=a				,						hidden_states=outputs.hidden_states     )






import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
				import torch

				from ..models.auto.modeling_auto import (
				    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
				    MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
				)

if is_tf_available() and is_tensorflow_probability_available():
				import tensorflow as tf
				import tensorflow_probability as tfp

				from ..models.auto.modeling_tf_auto import (
				    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
				    TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
				)



class  _a  (					lowercase__				):






							"""simple docstring"""

							def __call__(   self					:  List[Any]				,						a					:  str=None				,						a					:  Dict=None				,						**a					:  Tuple     )						->Dict:
													# Returns tqa_pipeline_inputs of shape:
													# [
													#   {"table": pd.DataFrame, "query": List[str]},
													#   ...,
													#   {"table": pd.DataFrame, "query" : List[str]}
													# ]
													requires_backends(self				,						"pandas"     )
													import pandas as pd

													if table is None:
																			raise ValueError("Keyword argument `table` cannot be None."     )
													elif query is None:
																			if isinstance(a				,						a     ) and table.get("query"     ) is not None and table.get("table"     ) is not None:
																									SCREAMING_SNAKE_CASE__  :					int =       [table]
																			elif isinstance(a				,						a     ) and len(a     ) > 0:
																									if not all(isinstance(a				,						a     ) for d in table     ):
																															raise ValueError(
																															    f"""Keyword argument `table` should be a list of dict, but is {(type(a     ) for d in table)}"""     )

																									if table[0].get("query"     ) is not None and table[0].get("table"     ) is not None:
																															SCREAMING_SNAKE_CASE__  :					List[str] =       table
																									else:
																															raise ValueError(
																															    "If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`"
																															    f""" and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys."""     )
																			elif Dataset is not None and isinstance(a				,						a     ) or isinstance(a				,						types.GeneratorType     ):
																									return table
																			else:
																									raise ValueError(
																									    "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
																									    f"""is {type(a     )})"""     )
													else:
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       [{"table": table, "query": query}]

													for tqa_pipeline_input in tqa_pipeline_inputs:
																			if not isinstance(tqa_pipeline_input["table"]				,						pd.DataFrame     ):
																									if tqa_pipeline_input["table"] is None:
																															raise ValueError("Table cannot be None."     )

																									SCREAMING_SNAKE_CASE__  :					Dict =       pd.DataFrame(tqa_pipeline_input["table"]     )

													return tqa_pipeline_inputs







@add_end_docstrings(lowercase__				)
class  _a  (					lowercase__				):






							"""simple docstring"""

							snake_case_							=    "table,query"

							def __init__(   self					:  List[str]				,						a					:  Optional[int]=TableQuestionAnsweringArgumentHandler()				,						*a					:  List[str]				,						**a					:  Dict     )						->Any:
													super().__init__(*a				,						**a     )
													SCREAMING_SNAKE_CASE__  :					Tuple =       args_parser

													self.check_model_type(
													    dict(
													        TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
													        + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()     )
													    if self.framework == "tf"
													    else dict(
													        MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()     )     )

													SCREAMING_SNAKE_CASE__  :					str =       bool(getattr(self.model.config				,						"aggregation_labels"				,						a     )     ) and bool(
													    getattr(self.model.config				,						"num_aggregation_labels"				,						a     )     )
													SCREAMING_SNAKE_CASE__  :					int =       "tapas" if hasattr(self.model.config				,						"aggregation_labels"     ) else None

							def   A_	(   self					:  List[str]				,						**a					:  Any     )						->Optional[Any]:
													return self.model(**a     )

							def   A_	(   self					:  Any				,						**a					:  Any     )						->Dict:
													if self.framework == "pt":
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       []
																			SCREAMING_SNAKE_CASE__  :					int =       []
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       None
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       inputs["input_ids"].shape[0]

																			SCREAMING_SNAKE_CASE__  :					int =       inputs["input_ids"].to(self.device     )
																			SCREAMING_SNAKE_CASE__  :					int =       inputs["attention_mask"].to(self.device     )
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       inputs["token_type_ids"].to(self.device     )
																			SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       None

																			for index in range(a     ):
																									# If sequences have already been processed, the token type IDs will be created according to the previous
																									# answer.
																									if prev_answers is not None:
																															SCREAMING_SNAKE_CASE__  :					Tuple =       token_type_ids_example[:, 3]  # shape (seq_len,)
																															SCREAMING_SNAKE_CASE__  :					Optional[Any] =       np.zeros_like(prev_labels_example.cpu().numpy()     )  # shape (seq_len,)

																															SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       token_type_ids[index]  # shape (seq_len, 7)
																															for i in range(model_labels.shape[0]     ):
																																					SCREAMING_SNAKE_CASE__  :					int =       token_type_ids_example[:, 0].tolist()[i]
																																					SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       token_type_ids_example[:, 1].tolist()[i] - 1
																																					SCREAMING_SNAKE_CASE__  :					Dict =       token_type_ids_example[:, 2].tolist()[i] - 1

																																					if row_id >= 0 and col_id >= 0 and segment_id == 1:
																																											SCREAMING_SNAKE_CASE__  :					Dict =       int(prev_answers[(col_id, row_id)]     )

																															SCREAMING_SNAKE_CASE__  :					Dict =       torch.from_numpy(a     ).type(torch.long     ).to(self.device     )

																									SCREAMING_SNAKE_CASE__  :					Optional[int] =       input_ids[index]
																									SCREAMING_SNAKE_CASE__  :					Any =       attention_mask[index]  # shape (seq_len,)
																									SCREAMING_SNAKE_CASE__  :					List[str] =       token_type_ids[index]  # shape (seq_len, 7)
																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       self.model(
																									    input_ids=input_ids_example.unsqueeze(0     )				,						attention_mask=attention_mask_example.unsqueeze(0     )				,						token_type_ids=token_type_ids_example.unsqueeze(0     )				,						)
																									SCREAMING_SNAKE_CASE__  :					Any =       outputs.logits

																									if self.aggregate:
																															all_aggregations.append(outputs.logits_aggregation     )

																									all_logits.append(a     )

																									SCREAMING_SNAKE_CASE__  :					Any =       torch.distributions.Bernoulli(logits=a     )
																									SCREAMING_SNAKE_CASE__  :					Tuple =       dist_per_token.probs * attention_mask_example.type(torch.floataa     ).to(
																									    dist_per_token.probs.device     )

																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       collections.defaultdict(a     )
																									for i, p in enumerate(probabilities.squeeze().tolist()     ):
																															SCREAMING_SNAKE_CASE__  :					List[Any] =       token_type_ids_example[:, 0].tolist()[i]
																															SCREAMING_SNAKE_CASE__  :					Dict =       token_type_ids_example[:, 1].tolist()[i] - 1
																															SCREAMING_SNAKE_CASE__  :					Optional[Any] =       token_type_ids_example[:, 2].tolist()[i] - 1
																															if col >= 0 and row >= 0 and segment_id == 1:
																																					coords_to_probs[(col, row)].append(a     )

																									SCREAMING_SNAKE_CASE__  :					Tuple =       {key: np.array(coords_to_probs[key]     ).mean() > 0.5 for key in coords_to_probs}

																			SCREAMING_SNAKE_CASE__  :					List[str] =       torch.cat(tuple(a     )				,						0     )

																			return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(a     )				,						0     ))
													else:
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       []
																			SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       []
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       None
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       inputs["input_ids"].shape[0]

																			SCREAMING_SNAKE_CASE__  :					Tuple =       inputs["input_ids"]
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       inputs["attention_mask"]
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       inputs["token_type_ids"].numpy()
																			SCREAMING_SNAKE_CASE__  :					Tuple =       None

																			for index in range(a     ):
																									# If sequences have already been processed, the token type IDs will be created according to the previous
																									# answer.
																									if prev_answers is not None:
																															SCREAMING_SNAKE_CASE__  :					Dict =       token_type_ids_example[:, 3]  # shape (seq_len,)
																															SCREAMING_SNAKE_CASE__  :					List[Any] =       np.zeros_like(a				,						dtype=np.intaa     )  # shape (seq_len,)

																															SCREAMING_SNAKE_CASE__  :					str =       token_type_ids[index]  # shape (seq_len, 7)
																															for i in range(model_labels.shape[0]     ):
																																					SCREAMING_SNAKE_CASE__  :					str =       token_type_ids_example[:, 0].tolist()[i]
																																					SCREAMING_SNAKE_CASE__  :					Any =       token_type_ids_example[:, 1].tolist()[i] - 1
																																					SCREAMING_SNAKE_CASE__  :					Dict =       token_type_ids_example[:, 2].tolist()[i] - 1

																																					if row_id >= 0 and col_id >= 0 and segment_id == 1:
																																											SCREAMING_SNAKE_CASE__  :					int =       int(prev_answers[(col_id, row_id)]     )

																															SCREAMING_SNAKE_CASE__  :					Any =       model_labels

																									SCREAMING_SNAKE_CASE__  :					Optional[Any] =       input_ids[index]
																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       attention_mask[index]  # shape (seq_len,)
																									SCREAMING_SNAKE_CASE__  :					Any =       token_type_ids[index]  # shape (seq_len, 7)
																									SCREAMING_SNAKE_CASE__  :					Any =       self.model(
																									    input_ids=np.expand_dims(a				,						axis=0     )				,						attention_mask=np.expand_dims(a				,						axis=0     )				,						token_type_ids=np.expand_dims(a				,						axis=0     )				,						)
																									SCREAMING_SNAKE_CASE__  :					str =       outputs.logits

																									if self.aggregate:
																															all_aggregations.append(outputs.logits_aggregation     )

																									all_logits.append(a     )

																									SCREAMING_SNAKE_CASE__  :					int =       tfp.distributions.Bernoulli(logits=a     )
																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       dist_per_token.probs_parameter() * tf.cast(a				,						tf.floataa     )

																									SCREAMING_SNAKE_CASE__  :					Tuple =       collections.defaultdict(a     )
																									SCREAMING_SNAKE_CASE__  :					Optional[Any] =       token_type_ids_example
																									for i, p in enumerate(tf.squeeze(a     ).numpy().tolist()     ):
																															SCREAMING_SNAKE_CASE__  :					str =       token_type_ids_example[:, 0].tolist()[i]
																															SCREAMING_SNAKE_CASE__  :					List[Any] =       token_type_ids_example[:, 1].tolist()[i] - 1
																															SCREAMING_SNAKE_CASE__  :					Optional[Any] =       token_type_ids_example[:, 2].tolist()[i] - 1
																															if col >= 0 and row >= 0 and segment_id == 1:
																																					coords_to_probs[(col, row)].append(a     )

																									SCREAMING_SNAKE_CASE__  :					int =       {key: np.array(coords_to_probs[key]     ).mean() > 0.5 for key in coords_to_probs}

																			SCREAMING_SNAKE_CASE__  :					List[Any] =       tf.concat(tuple(a     )				,						0     )

																			return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(a     )				,						0     ))

							def __call__(   self					:  Optional[Any]				,						*a					:  Any				,						**a					:  Optional[int]     )						->Dict:
													SCREAMING_SNAKE_CASE__  :					Tuple =       self._args_parser(*a				,						**a     )

													SCREAMING_SNAKE_CASE__  :					Dict =       super().__call__(a				,						**a     )
													if len(a     ) == 1:
																			return results[0]
													return results

							def   A_	(   self					:  Any				,						a					:  Dict=None				,						a					:  Dict=None				,						a					:  Union[str, Any]=None				,						**a					:  int     )						->Any:
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       {}
													if padding is not None:
																			SCREAMING_SNAKE_CASE__  :					Optional[int] =       padding
													if truncation is not None:
																			SCREAMING_SNAKE_CASE__  :					int =       truncation

													SCREAMING_SNAKE_CASE__  :					Optional[int] =       {}
													if sequential is not None:
																			SCREAMING_SNAKE_CASE__  :					int =       sequential
													return preprocess_params, forward_params, {}

							def   A_	(   self					:  Any				,						a					:  Any				,						a					:  Union[str, Any]=None				,						a					:  Union[str, Any]=True				,						a					:  Dict=None     )						->int:
													if truncation is None:
																			if self.type == "tapas":
																									SCREAMING_SNAKE_CASE__  :					Any =       "drop_rows_to_fit"
																			else:
																									SCREAMING_SNAKE_CASE__  :					List[str] =       "do_not_truncate"

													SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__  :					List[Any] =       pipeline_input["table"], pipeline_input["query"]
													if table.empty:
																			raise ValueError("table is empty"     )
													if query is None or query == "":
																			raise ValueError("query is empty"     )
													SCREAMING_SNAKE_CASE__  :					Tuple =       self.tokenizer(a				,						a				,						return_tensors=self.framework				,						truncation=a				,						padding=a     )
													SCREAMING_SNAKE_CASE__  :					str =       table
													return inputs

							def   A_	(   self					:  Any				,						a					:  Tuple				,						a					:  Union[str, Any]=False     )						->Union[str, Any]:
													SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       model_inputs.pop("table"     )

													if self.type == "tapas":
																			if sequential:
																									SCREAMING_SNAKE_CASE__  :					List[str] =       self.sequential_inference(**a     )
																			else:
																									SCREAMING_SNAKE_CASE__  :					List[Any] =       self.batch_inference(**a     )
													else:
																			SCREAMING_SNAKE_CASE__  :					Optional[Any] =       self.model.generate(**a     )
													SCREAMING_SNAKE_CASE__  :					str =       {"model_inputs": model_inputs, "table": table, "outputs": outputs}
													return model_outputs






							def   A_	(   self					:  str				,						a					:  Any     )						->Tuple:
													SCREAMING_SNAKE_CASE__  :					Dict =       model_outputs["model_inputs"]
													SCREAMING_SNAKE_CASE__  :					Optional[Any] =       model_outputs["table"]
													SCREAMING_SNAKE_CASE__  :					Dict =       model_outputs["outputs"]
													if self.type == "tapas":
																			if self.aggregate:
																									SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__  :					List[str] =       outputs[:2]
																									SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.tokenizer.convert_logits_to_predictions(a				,						a				,						a     )
																									SCREAMING_SNAKE_CASE__,				SCREAMING_SNAKE_CASE__  :					Optional[Any] =       predictions
																									SCREAMING_SNAKE_CASE__  :					Tuple =       {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(a     )}

																									SCREAMING_SNAKE_CASE__  :					Tuple =       self.model.config.no_aggregation_label_index
																									SCREAMING_SNAKE_CASE__  :					List[Any] =       {
																									    i: aggregators[i] + " > " for i, pred in enumerate(a     ) if pred != no_agg_label_index
																									}
																			else:
																									SCREAMING_SNAKE_CASE__  :					Optional[Any] =       outputs[0]
																									SCREAMING_SNAKE_CASE__  :					Optional[int] =       self.tokenizer.convert_logits_to_predictions(a				,						a     )
																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       predictions[0]
																									SCREAMING_SNAKE_CASE__  :					Dict =       {}
																									SCREAMING_SNAKE_CASE__  :					Dict =       {}
																			SCREAMING_SNAKE_CASE__  :					List[str] =       []
																			for index, coordinates in enumerate(a     ):
																									SCREAMING_SNAKE_CASE__  :					int =       [table.iat[coordinate] for coordinate in coordinates]
																									SCREAMING_SNAKE_CASE__  :					int =       aggregators.get(a				,						""     )
																									SCREAMING_SNAKE_CASE__  :					Union[str, Any] =       aggregators_prefix.get(a				,						""     )
																									SCREAMING_SNAKE_CASE__  :					Any =       {
																									    "answer": aggregator_prefix + ", ".join(a     ),
																									    "coordinates": coordinates,
																									    "cells": [table.iat[coordinate] for coordinate in coordinates],
																									}
																									if aggregator:
																															SCREAMING_SNAKE_CASE__  :					Optional[Any] =       aggregator

																									answers.append(a     )
																			if len(a     ) == 0:
																									raise PipelineException("Empty answer"     )
													else:
																			SCREAMING_SNAKE_CASE__  :					List[Any] =       [{"answer": answer} for answer in self.tokenizer.batch_decode(a				,						skip_special_tokens=a     )]

													return answers if len(a     ) > 1 else answers[0]