import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


_SCREAMING_SNAKE_CASE:    str     						=							'''1.5.0'''

_SCREAMING_SNAKE_CASE:    Tuple     						=							['''vision-encoder-decoder''']






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





			if is_optimum_available():
						from optimum.version import __version__ as optimum_version

						_snake_case														=   version.parse(lowerCamelCase_	)
						if parsed_optimum_version < version.parse(lowerCamelCase_	):
									raise RuntimeError(
									    f'transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You '
									    "can upgrade optimum by running: pip install -U optimum[exporters]"	)
			else:
						raise RuntimeError(
						    "transformers.onnx requires optimum to run, you can install the library by running: pip install "
						    "optimum[exporters]"	)
			_snake_case														=   [
			    sys.executable,
			    "-m",
			    "optimum.exporters.onnx",
			    f'--model {args.model}',
			    f'--task {args.feature}',
			    f'--framework {args.framework}' if args.framework is not None else "",
			    f'{args.output}',
			]
			_snake_case														=   subprocess.Popen(" ".join(lowerCamelCase_	)				,						stdout=subprocess.PIPE				,						shell=lowerCamelCase_	)
			proc.wait()

			logger.info(
			    "The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as "
			    "transformers.onnx is deprecated, and will be removed in v5. You can find more information here: "
			    "https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."	)






def  UpperCAmelCase__(    lowerCamelCase_	):



			"""simple docstring"""





			_snake_case														=   args.output if args.output.is_file() else args.output.joinpath("model.onnx"	)
			if not args.output.parent.exists():
						args.output.parent.mkdir(parents=lowerCamelCase_	)

			# Allocate the model
			_snake_case														=   FeaturesManager.get_model_from_feature(
			    args.feature				,						args.model				,						framework=args.framework				,						cache_dir=args.cache_dir	)

			_snake_case							,			_snake_case														=   FeaturesManager.check_supported_model_or_raise(lowerCamelCase_				,						feature=args.feature	)
			_snake_case														=   model_onnx_config(model.config	)

			if model_kind in ENCODER_DECODER_MODELS:
						_snake_case														=   model.get_encoder()
						_snake_case														=   model.get_decoder()

						_snake_case														=   onnx_config.get_encoder_config(encoder_model.config	)
						_snake_case														=   onnx_config.get_decoder_config(
						    encoder_model.config				,						decoder_model.config				,						feature=args.feature	)

						if args.opset is None:
									_snake_case														=   max(encoder_onnx_config.default_onnx_opset				,						decoder_onnx_config.default_onnx_opset	)

						if args.opset < min(encoder_onnx_config.default_onnx_opset				,						decoder_onnx_config.default_onnx_opset	):
									raise ValueError(
									    f'Opset {args.opset} is not sufficient to export {model_kind}. At least '
									    f' {min(encoder_onnx_config.default_onnx_opset				,						decoder_onnx_config.default_onnx_opset	)} is required.'	)

						_snake_case														=   AutoFeatureExtractor.from_pretrained(args.model	)

						_snake_case							,			_snake_case														=   export(
						    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.opset				,						args.output.parent.joinpath("encoder_model.onnx"	)				,						)

						validate_model_outputs(
						    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.output.parent.joinpath("encoder_model.onnx"	)				,						lowerCamelCase_				,						args.atol if args.atol else encoder_onnx_config.atol_for_validation				,						)

						_snake_case														=   AutoTokenizer.from_pretrained(args.model	)

						_snake_case							,			_snake_case														=   export(
						    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.opset				,						args.output.parent.joinpath("decoder_model.onnx"	)				,						)

						validate_model_outputs(
						    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.output.parent.joinpath("decoder_model.onnx"	)				,						lowerCamelCase_				,						args.atol if args.atol else decoder_onnx_config.atol_for_validation				,						)
						logger.info(
						    f'All good, model saved at: {args.output.parent.joinpath("encoder_model.onnx"	).as_posix()},'
						    f' {args.output.parent.joinpath("decoder_model.onnx"	).as_posix()}'	)

			else:
						# Instantiate the appropriate preprocessor
						if args.preprocessor == "auto":
									_snake_case														=   get_preprocessor(args.model	)
						elif args.preprocessor == "tokenizer":
									_snake_case														=   AutoTokenizer.from_pretrained(args.model	)
						elif args.preprocessor == "image_processor":
									_snake_case														=   AutoImageProcessor.from_pretrained(args.model	)
						elif args.preprocessor == "feature_extractor":
									_snake_case														=   AutoFeatureExtractor.from_pretrained(args.model	)
						elif args.preprocessor == "processor":
									_snake_case														=   AutoProcessor.from_pretrained(args.model	)
						else:
									raise ValueError(f'Unknown preprocessor type \'{args.preprocessor}\''	)

						# Ensure the requested opset is sufficient
						if args.opset is None:
									_snake_case														=   onnx_config.default_onnx_opset

						if args.opset < onnx_config.default_onnx_opset:
									raise ValueError(
									    f'Opset {args.opset} is not sufficient to export {model_kind}. '
									    f'At least  {onnx_config.default_onnx_opset} is required.'	)

						_snake_case							,			_snake_case														=   export(
						    lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.opset				,						args.output				,						)

						if args.atol is None:
									_snake_case														=   onnx_config.atol_for_validation

						validate_model_outputs(lowerCamelCase_				,						lowerCamelCase_				,						lowerCamelCase_				,						args.output				,						lowerCamelCase_				,						args.atol	)
						logger.info(f'All good, model saved at: {args.output.as_posix()}'	)
						warnings.warn(
						    "The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"
						    " using optimum.exporters.onnx in future. You can find more information here:"
						    " https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."				,						lowerCamelCase_				,						)






def  UpperCAmelCase__(    ):



			"""simple docstring"""





			_snake_case														=   ArgumentParser("Hugging Face Transformers ONNX exporter"	)
			parser.add_argument(
			    "-m"				,						"--model"				,						type=lowerCamelCase_				,						required=lowerCamelCase_				,						help="Model ID on huggingface.co or path on disk to load model from."	)
			parser.add_argument(
			    "--feature"				,						default="default"				,						help="The type of features to export the model with."				,						)
			parser.add_argument("--opset"				,						type=lowerCamelCase_				,						default=lowerCamelCase_				,						help="ONNX opset version to export the model with."	)
			parser.add_argument(
			    "--atol"				,						type=lowerCamelCase_				,						default=lowerCamelCase_				,						help="Absolute difference tolerance when validating the model."	)
			parser.add_argument(
			    "--framework"				,						type=lowerCamelCase_				,						choices=["pt", "tf"]				,						default=lowerCamelCase_				,						help=(
			        "The framework to use for the ONNX export."
			        " If not provided, will attempt to use the local checkpoint's original framework"
			        " or what is available in the environment."
			    )				,						)
			parser.add_argument("output"				,						type=lowerCamelCase_				,						help="Path indicating where to store generated ONNX model."	)
			parser.add_argument("--cache_dir"				,						type=lowerCamelCase_				,						default=lowerCamelCase_				,						help="Path indicating where to store cache."	)
			parser.add_argument(
			    "--preprocessor"				,						type=lowerCamelCase_				,						choices=["auto", "tokenizer", "feature_extractor", "image_processor", "processor"]				,						default="auto"				,						help="Which type of preprocessor to use. 'auto' tries to automatically detect it."				,						)
			parser.add_argument(
			    "--export_with_transformers"				,						action="store_true"				,						help=(
			        "Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be "
			        "useful when exporting a model supported in transformers but not in optimum, otherwise it is not "
			        "recommended."
			    )				,						)

			_snake_case														=   parser.parse_args()
			if args.export_with_transformers or not is_optimum_available():
						export_with_transformers(lowerCamelCase_	)
			else:
						export_with_optimum(lowerCamelCase_	)


if __name__ == "__main__":
			_SCREAMING_SNAKE_CASE:    Any     						=							logging.get_logger('''transformers.onnx''')  # pylint: disable=invalid-name
			logger.setLevel(logging.INFO)
			main()


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 						_SCREAMING_SNAKE_CASE				(  _lowercase				):






		"""simple docstring"""







		def __call__(      self     :					Union[str, Any]	,       __SCREAMING_SNAKE_CASE     :					int=None	,       __SCREAMING_SNAKE_CASE     :					str=None	,       **__SCREAMING_SNAKE_CASE     :					Union[str, Any] ):






					"""simple docstring"""
					# 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(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) and table.get("query" ) is not None and table.get("table" ) is not None:
											_snake_case														=   [table]
								elif isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) and len(__SCREAMING_SNAKE_CASE ) > 0:
											if not all(isinstance(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) for d in table ):
														raise ValueError(
														    F'Keyword argument `table` should be a list of dict, but is {(type(__SCREAMING_SNAKE_CASE ) for d in table)}' )

											if table[0].get("query" ) is not None and table[0].get("table" ) is not None:
														_snake_case														=   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(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE ) or isinstance(__SCREAMING_SNAKE_CASE	,       types.GeneratorType ):
											return table
								else:
											raise ValueError(
											    "Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but "
											    F'is {type(__SCREAMING_SNAKE_CASE )})' )
					else:
								_snake_case														=   [{"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." )

											_snake_case														=   pd.DataFrame(tqa_pipeline_input["table"] )

					return tqa_pipeline_inputs

@add_end_docstrings(_lowercase				)
class 						_SCREAMING_SNAKE_CASE				(  _lowercase				):






		"""simple docstring"""







		A_    			=   '''table,query'''



		def __init__(      self     :					Optional[Any]	,       __SCREAMING_SNAKE_CASE     :					Tuple=TableQuestionAnsweringArgumentHandler()	,       *__SCREAMING_SNAKE_CASE     :					Optional[int]	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					super().__init__(*__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )
					_snake_case														=   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() ) )

					_snake_case														=   bool(getattr(self.model.config	,       "aggregation_labels"	,       __SCREAMING_SNAKE_CASE ) ) and bool(
					    getattr(self.model.config	,       "num_aggregation_labels"	,       __SCREAMING_SNAKE_CASE ) )
					_snake_case														=   "tapas" if hasattr(self.model.config	,       "aggregation_labels" ) else None



		def 					_a					(      self     :					List[Any]	,       **__SCREAMING_SNAKE_CASE     :					str ):






					"""simple docstring"""
					return self.model(**__SCREAMING_SNAKE_CASE )



		def 					_a					(      self     :					Tuple	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					if self.framework == "pt":
								_snake_case														=   []
								_snake_case														=   []
								_snake_case														=   None
								_snake_case														=   inputs["input_ids"].shape[0]

								_snake_case														=   inputs["input_ids"].to(self.device )
								_snake_case														=   inputs["attention_mask"].to(self.device )
								_snake_case														=   inputs["token_type_ids"].to(self.device )
								_snake_case														=   None

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

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

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

														_snake_case														=   torch.from_numpy(__SCREAMING_SNAKE_CASE ).type(torch.long ).to(self.device )

											_snake_case														=   input_ids[index]
											_snake_case														=   attention_mask[index]  # shape (seq_len,)
											_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
											_snake_case														=   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 )	,       )
											_snake_case														=   outputs.logits

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

											all_logits.append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   torch.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE )
											_snake_case														=   dist_per_token.probs * attention_mask_example.type(torch.floataa ).to(
											    dist_per_token.probs.device )

											_snake_case														=   collections.defaultdict(__SCREAMING_SNAKE_CASE )
											for i, p in enumerate(probabilities.squeeze().tolist() ):
														_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
														_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
														_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1
														if col >= 0 and row >= 0 and segment_id == 1:
																	coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE )

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

								_snake_case														=   torch.cat(tuple(__SCREAMING_SNAKE_CASE )	,       0 )

								return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(__SCREAMING_SNAKE_CASE )	,       0 ))
					else:
								_snake_case														=   []
								_snake_case														=   []
								_snake_case														=   None
								_snake_case														=   inputs["input_ids"].shape[0]

								_snake_case														=   inputs["input_ids"]
								_snake_case														=   inputs["attention_mask"]
								_snake_case														=   inputs["token_type_ids"].numpy()
								_snake_case														=   None

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

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

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

														_snake_case														=   model_labels

											_snake_case														=   input_ids[index]
											_snake_case														=   attention_mask[index]  # shape (seq_len,)
											_snake_case														=   token_type_ids[index]  # shape (seq_len, 7)
											_snake_case														=   self.model(
											    input_ids=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       attention_mask=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       token_type_ids=np.expand_dims(__SCREAMING_SNAKE_CASE	,       axis=0 )	,       )
											_snake_case														=   outputs.logits

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

											all_logits.append(__SCREAMING_SNAKE_CASE )

											_snake_case														=   tfp.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE )
											_snake_case														=   dist_per_token.probs_parameter() * tf.cast(__SCREAMING_SNAKE_CASE	,       tf.floataa )

											_snake_case														=   collections.defaultdict(__SCREAMING_SNAKE_CASE )
											_snake_case														=   token_type_ids_example
											for i, p in enumerate(tf.squeeze(__SCREAMING_SNAKE_CASE ).numpy().tolist() ):
														_snake_case														=   token_type_ids_example[:, 0].tolist()[i]
														_snake_case														=   token_type_ids_example[:, 1].tolist()[i] - 1
														_snake_case														=   token_type_ids_example[:, 2].tolist()[i] - 1
														if col >= 0 and row >= 0 and segment_id == 1:
																	coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE )

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

								_snake_case														=   tf.concat(tuple(__SCREAMING_SNAKE_CASE )	,       0 )

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



		def __call__(      self     :					str	,       *__SCREAMING_SNAKE_CASE     :					Optional[int]	,       **__SCREAMING_SNAKE_CASE     :					List[Any] ):






					"""simple docstring"""
					_snake_case														=   self._args_parser(*__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )

					_snake_case														=   super().__call__(__SCREAMING_SNAKE_CASE	,       **__SCREAMING_SNAKE_CASE )
					if len(__SCREAMING_SNAKE_CASE ) == 1:
								return results[0]
					return results



		def 					_a					(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					Optional[int]=None	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=None	,       __SCREAMING_SNAKE_CASE     :					str=None	,       **__SCREAMING_SNAKE_CASE     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   {}
					if padding is not None:
								_snake_case														=   padding
					if truncation is not None:
								_snake_case														=   truncation

					_snake_case														=   {}
					if sequential is not None:
								_snake_case														=   sequential
					return preprocess_params, forward_params, {}



		def 					_a					(      self     :					Any	,       __SCREAMING_SNAKE_CASE     :					Tuple	,       __SCREAMING_SNAKE_CASE     :					Optional[Any]=None	,       __SCREAMING_SNAKE_CASE     :					Union[str, Any]=True	,       __SCREAMING_SNAKE_CASE     :					str=None ):






					"""simple docstring"""
					if truncation is None:
								if self.type == "tapas":
											_snake_case														=   "drop_rows_to_fit"
								else:
											_snake_case														=   "do_not_truncate"

					_snake_case							,			_snake_case														=   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" )
					_snake_case														=   self.tokenizer(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       return_tensors=self.framework	,       truncation=__SCREAMING_SNAKE_CASE	,       padding=__SCREAMING_SNAKE_CASE )
					_snake_case														=   table
					return inputs



		def 					_a					(      self     :					Optional[int]	,       __SCREAMING_SNAKE_CASE     :					str	,       __SCREAMING_SNAKE_CASE     :					List[Any]=False ):






					"""simple docstring"""
					_snake_case														=   model_inputs.pop("table" )

					if self.type == "tapas":
								if sequential:
											_snake_case														=   self.sequential_inference(**__SCREAMING_SNAKE_CASE )
								else:
											_snake_case														=   self.batch_inference(**__SCREAMING_SNAKE_CASE )
					else:
								_snake_case														=   self.model.generate(**__SCREAMING_SNAKE_CASE )
					_snake_case														=   {"model_inputs": model_inputs, "table": table, "outputs": outputs}
					return model_outputs







		def 					_a					(      self     :					Dict	,       __SCREAMING_SNAKE_CASE     :					Optional[int] ):






					"""simple docstring"""
					_snake_case														=   model_outputs["model_inputs"]
					_snake_case														=   model_outputs["table"]
					_snake_case														=   model_outputs["outputs"]
					if self.type == "tapas":
								if self.aggregate:
											_snake_case							,			_snake_case														=   outputs[:2]
											_snake_case														=   self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case							,			_snake_case														=   predictions
											_snake_case														=   {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(__SCREAMING_SNAKE_CASE )}

											_snake_case														=   self.model.config.no_aggregation_label_index
											_snake_case														=   {
											    i: aggregators[i] + " > " for i, pred in enumerate(__SCREAMING_SNAKE_CASE ) if pred != no_agg_label_index
											}
								else:
											_snake_case														=   outputs[0]
											_snake_case														=   self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE	,       __SCREAMING_SNAKE_CASE )
											_snake_case														=   predictions[0]
											_snake_case														=   {}
											_snake_case														=   {}
								_snake_case														=   []
								for index, coordinates in enumerate(__SCREAMING_SNAKE_CASE ):
											_snake_case														=   [table.iat[coordinate] for coordinate in coordinates]
											_snake_case														=   aggregators.get(__SCREAMING_SNAKE_CASE	,       "" )
											_snake_case														=   aggregators_prefix.get(__SCREAMING_SNAKE_CASE	,       "" )
											_snake_case														=   {
											    "answer": aggregator_prefix + ", ".join(__SCREAMING_SNAKE_CASE ),
											    "coordinates": coordinates,
											    "cells": [table.iat[coordinate] for coordinate in coordinates],
											}
											if aggregator:
														_snake_case														=   aggregator

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

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

