
"""simple docstring"""

import unittest

import numpy as np
import timeout_decorator  # noqa

from transformers import MarianConfig, is_flax_available
from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, slow
from transformers.utils import cached_property

from ...generation.test_flax_utils import FlaxGenerationTesterMixin
from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor


if is_flax_available():
					import os

					# The slow tests are often failing with OOM error on GPU
					# This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
					# but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
					_A				=					'platform'

					import jax
					import jax.numpy as jnp

					from transformers import MarianTokenizer
					from transformers.models.marian.modeling_flax_marian import FlaxMarianModel, FlaxMarianMTModel, shift_tokens_right
def 						UpperCAmelCase   (						a_,		a_,		a_=None,		a_=None,		a_=None,		a_=None,		a_=None,		a_=None,		):





		'''simple docstring'''


		if attention_mask is None:
				lowerCamelCase	:     Any            =       np.where(input_ids != config.pad_token_id,		1,		0     )
		if decoder_attention_mask is None:
				lowerCamelCase	:     List[str]            =       np.where(decoder_input_ids != config.pad_token_id,		1,		0     )
		if head_mask is None:
				lowerCamelCase	:     Optional[Any]            =       np.ones((config.encoder_layers, config.encoder_attention_heads)     )
		if decoder_head_mask is None:
				lowerCamelCase	:     int            =       np.ones((config.decoder_layers, config.decoder_attention_heads)     )
		if cross_attn_head_mask is None:
				lowerCamelCase	:     str            =       np.ones((config.decoder_layers, config.decoder_attention_heads)     )
		return {
		    "input_ids": input_ids,
		    "decoder_input_ids": decoder_input_ids,
		    "attention_mask": attention_mask,
		    "decoder_attention_mask": attention_mask,
		}






class 			_lowercase  :




	def __init__(					self						,					UpperCAmelCase_						,					UpperCAmelCase_=13						,					UpperCAmelCase_=7						,					UpperCAmelCase_=True						,					UpperCAmelCase_=False						,					UpperCAmelCase_=99						,					UpperCAmelCase_=16						,					UpperCAmelCase_=2						,					UpperCAmelCase_=4						,					UpperCAmelCase_=4						,					UpperCAmelCase_="gelu"						,					UpperCAmelCase_=0.1						,					UpperCAmelCase_=0.1						,					UpperCAmelCase_=32						,					UpperCAmelCase_=2						,					UpperCAmelCase_=1						,					UpperCAmelCase_=0						,					UpperCAmelCase_=0.02						,					)						->				List[str]:
			lowerCamelCase	:     Optional[Any]            =       parent
			lowerCamelCase	:     List[Any]            =       batch_size
			lowerCamelCase	:     Optional[Any]            =       seq_length
			lowerCamelCase	:     Optional[int]            =       is_training
			lowerCamelCase	:     Union[str, Any]            =       use_labels
			lowerCamelCase	:     int            =       vocab_size
			lowerCamelCase	:     str            =       hidden_size
			lowerCamelCase	:     Tuple            =       num_hidden_layers
			lowerCamelCase	:     str            =       num_attention_heads
			lowerCamelCase	:     Optional[Any]            =       intermediate_size
			lowerCamelCase	:     Optional[Any]            =       hidden_act
			lowerCamelCase	:     Any            =       hidden_dropout_prob
			lowerCamelCase	:     int            =       attention_probs_dropout_prob
			lowerCamelCase	:     List[str]            =       max_position_embeddings
			lowerCamelCase	:     Any            =       eos_token_id
			lowerCamelCase	:     Union[str, Any]            =       pad_token_id
			lowerCamelCase	:     Optional[Any]            =       bos_token_id
			lowerCamelCase	:     Optional[int]            =       initializer_range




	def      _UpperCamelCase       (					self   )						->				Dict:
			lowerCamelCase	:     Tuple            =       np.clip(ids_tensor([self.batch_size, self.seq_length - 1]						,					self.vocab_size   )						,					3						,					self.vocab_size   )
			lowerCamelCase	:     str            =       np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1)						,					dtype=np.intaa   ))						,					-1   )

			lowerCamelCase	:     List[str]            =       shift_tokens_right(UpperCAmelCase_						,					1						,					2   )

			lowerCamelCase	:     int            =       MarianConfig(
			    vocab_size=self.vocab_size						,					d_model=self.hidden_size						,					encoder_layers=self.num_hidden_layers						,					decoder_layers=self.num_hidden_layers						,					encoder_attention_heads=self.num_attention_heads						,					decoder_attention_heads=self.num_attention_heads						,					encoder_ffn_dim=self.intermediate_size						,					decoder_ffn_dim=self.intermediate_size						,					dropout=self.hidden_dropout_prob						,					attention_dropout=self.attention_probs_dropout_prob						,					max_position_embeddings=self.max_position_embeddings						,					eos_token_id=self.eos_token_id						,					bos_token_id=self.bos_token_id						,					pad_token_id=self.pad_token_id						,					initializer_range=self.initializer_range						,					use_cache=UpperCAmelCase_						,					)
			lowerCamelCase	:     Tuple            =       prepare_marian_inputs_dict(UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )
			return config, inputs_dict




	def      _UpperCamelCase       (					self   )						->				Any:
			lowerCamelCase      ,       lowerCamelCase	:     int            =       self.prepare_config_and_inputs()
			return config, inputs_dict




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				Union[str, Any]:
			lowerCamelCase	:     Optional[Any]            =       20
			lowerCamelCase	:     int            =       model_class_name(UpperCAmelCase_   )

			lowerCamelCase	:     Optional[Any]            =       model.encode(inputs_dict['input_ids']   )

			lowerCamelCase      ,       lowerCamelCase	:     List[Any]            =       (
			    inputs_dict['decoder_input_ids'],
			    inputs_dict['decoder_attention_mask'],
			)

			lowerCamelCase	:     Dict            =       model.init_cache(decoder_input_ids.shape[0]						,					UpperCAmelCase_						,					UpperCAmelCase_   )
			lowerCamelCase	:     Any            =       jnp.ones((decoder_input_ids.shape[0], max_decoder_length)						,					dtype='i4'   )

			lowerCamelCase	:     List[Any]            =       jnp.broadcast_to(
			    jnp.arange(decoder_input_ids.shape[-1] - 1   )[None, :]						,					(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,					)
			lowerCamelCase	:     int            =       model.decode(
			    decoder_input_ids[:, :-1]						,					UpperCAmelCase_						,					decoder_attention_mask=UpperCAmelCase_						,					past_key_values=UpperCAmelCase_						,					decoder_position_ids=UpperCAmelCase_						,					)

			lowerCamelCase	:     int            =       jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,					dtype='i4'   )
			lowerCamelCase	:     Dict            =       model.decode(
			    decoder_input_ids[:, -1:]						,					UpperCAmelCase_						,					decoder_attention_mask=UpperCAmelCase_						,					past_key_values=outputs_cache.past_key_values						,					decoder_position_ids=UpperCAmelCase_						,					)

			lowerCamelCase	:     Optional[int]            =       model.decode(UpperCAmelCase_						,					UpperCAmelCase_   )

			lowerCamelCase	:     Tuple            =       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
			self.parent.assertTrue(diff < 1E-3						,					msg=F"""Max diff is {diff}"""   )




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )						->				Union[str, Any]:
			lowerCamelCase	:     Optional[int]            =       20
			lowerCamelCase	:     Optional[int]            =       model_class_name(UpperCAmelCase_   )

			lowerCamelCase	:     Optional[int]            =       model.encode(inputs_dict['input_ids']   )

			lowerCamelCase      ,       lowerCamelCase	:     Optional[int]            =       (
			    inputs_dict['decoder_input_ids'],
			    inputs_dict['decoder_attention_mask'],
			)

			lowerCamelCase	:     Tuple            =       jnp.concatenate(
			    [
			        decoder_attention_mask,
			        jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])   ),
			    ]						,					axis=-1						,					)

			lowerCamelCase	:     Tuple            =       model.init_cache(decoder_input_ids.shape[0]						,					UpperCAmelCase_						,					UpperCAmelCase_   )
			lowerCamelCase	:     List[str]            =       jnp.broadcast_to(
			    jnp.arange(decoder_input_ids.shape[-1] - 1   )[None, :]						,					(decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1)						,					)

			lowerCamelCase	:     int            =       model.decode(
			    decoder_input_ids[:, :-1]						,					UpperCAmelCase_						,					decoder_attention_mask=UpperCAmelCase_						,					past_key_values=UpperCAmelCase_						,					decoder_position_ids=UpperCAmelCase_						,					)
			lowerCamelCase	:     Union[str, Any]            =       jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]]						,					dtype='i4'   )
			lowerCamelCase	:     Dict            =       model.decode(
			    decoder_input_ids[:, -1:]						,					UpperCAmelCase_						,					past_key_values=outputs_cache.past_key_values						,					decoder_attention_mask=UpperCAmelCase_						,					decoder_position_ids=UpperCAmelCase_						,					)

			lowerCamelCase	:     int            =       model.decode(UpperCAmelCase_						,					UpperCAmelCase_						,					decoder_attention_mask=UpperCAmelCase_   )

			lowerCamelCase	:     Dict            =       np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])   )   )
			self.parent.assertTrue(diff < 1E-3						,					msg=F"""Max diff is {diff}"""   )






@require_flax
class 			_lowercase  (							__UpperCAmelCase							,			unittest.TestCase							,			__UpperCAmelCase						):
	lowercase_								=      True
	lowercase_								=      (FlaxMarianModel, FlaxMarianMTModel) if is_flax_available() else ()
	lowercase_								=      (FlaxMarianMTModel,) if is_flax_available() else ()




	def      _UpperCamelCase       (					self   )						->				List[Any]:
			lowerCamelCase	:     int            =       FlaxMarianModelTester(self   )




	def      _UpperCamelCase       (					self   )						->				List[str]:
			lowerCamelCase      ,       lowerCamelCase	:     str            =       self.model_tester.prepare_config_and_inputs()
			for model_class in self.all_model_classes:
					self.model_tester.check_use_cache_forward(UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )




	def      _UpperCamelCase       (					self   )						->				Any:
			lowerCamelCase      ,       lowerCamelCase	:     List[str]            =       self.model_tester.prepare_config_and_inputs()
			for model_class in self.all_model_classes:
					self.model_tester.check_use_cache_forward_with_attn_mask(UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   )




	def      _UpperCamelCase       (					self   )						->				int:
			lowerCamelCase      ,       lowerCamelCase	:     Tuple            =       self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					with self.subTest(model_class.__name__   ):
							lowerCamelCase	:     Optional[Any]            =       self._prepare_for_class(UpperCAmelCase_						,					UpperCAmelCase_   )
							lowerCamelCase	:     List[Any]            =       model_class(UpperCAmelCase_   )

							@jax.jit
							def encode_jitted(UpperCAmelCase_						,					UpperCAmelCase_=None						,					**UpperCAmelCase_   ):
									return model.encode(input_ids=UpperCAmelCase_						,					attention_mask=UpperCAmelCase_   )

							with self.subTest('JIT Enabled'   ):
									lowerCamelCase	:     Optional[Any]            =       encode_jitted(**UpperCAmelCase_   ).to_tuple()

							with self.subTest('JIT Disabled'   ):
									with jax.disable_jit():
											lowerCamelCase	:     int            =       encode_jitted(**UpperCAmelCase_   ).to_tuple()

							self.assertEqual(len(UpperCAmelCase_   )						,					len(UpperCAmelCase_   )   )
							for jitted_output, output in zip(UpperCAmelCase_						,					UpperCAmelCase_   ):
									self.assertEqual(jitted_output.shape						,					output.shape   )




	def      _UpperCamelCase       (					self   )						->				Dict:
			lowerCamelCase      ,       lowerCamelCase	:     List[str]            =       self.model_tester.prepare_config_and_inputs_for_common()

			for model_class in self.all_model_classes:
					with self.subTest(model_class.__name__   ):
							lowerCamelCase	:     Tuple            =       model_class(UpperCAmelCase_   )
							lowerCamelCase	:     Tuple            =       model.encode(inputs_dict['input_ids']						,					inputs_dict['attention_mask']   )

							lowerCamelCase	:     Dict            =       {
							    'decoder_input_ids': inputs_dict['decoder_input_ids'],
							    'decoder_attention_mask': inputs_dict['decoder_attention_mask'],
							    'encoder_outputs': encoder_outputs,
							}

							@jax.jit
							def decode_jitted(UpperCAmelCase_						,					UpperCAmelCase_						,					UpperCAmelCase_   ):
									return model.decode(
									    decoder_input_ids=UpperCAmelCase_						,					decoder_attention_mask=UpperCAmelCase_						,					encoder_outputs=UpperCAmelCase_						,					)

							with self.subTest('JIT Enabled'   ):
									lowerCamelCase	:     Optional[int]            =       decode_jitted(**UpperCAmelCase_   ).to_tuple()

							with self.subTest('JIT Disabled'   ):
									with jax.disable_jit():
											lowerCamelCase	:     Any            =       decode_jitted(**UpperCAmelCase_   ).to_tuple()

							self.assertEqual(len(UpperCAmelCase_   )						,					len(UpperCAmelCase_   )   )
							for jitted_output, output in zip(UpperCAmelCase_						,					UpperCAmelCase_   ):
									self.assertEqual(jitted_output.shape						,					output.shape   )




	@slow
	def      _UpperCamelCase       (					self   )						->				Tuple:
			for model_class_name in self.all_model_classes:
					lowerCamelCase	:     str            =       model_class_name.from_pretrained('Helsinki-NLP/opus-mt-en-de'   )
					# FlaxMarianForSequenceClassification expects eos token in input_ids
					lowerCamelCase	:     Optional[int]            =       np.ones((1, 1)   ) * model.config.eos_token_id
					lowerCamelCase	:     List[Any]            =       model(UpperCAmelCase_   )
					self.assertIsNotNone(UpperCAmelCase_   )






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							unittest.TestCase						):
	lowercase_								=      None
	lowercase_								=      None




	@classmethod
	def      _UpperCamelCase       (					cls   )						->				None:
			lowerCamelCase	:     Dict            =       F"""Helsinki-NLP/opus-mt-{cls.src}-{cls.tgt}"""
			return cls




	@cached_property
	def      _UpperCamelCase       (					self   )						->				int:
			return MarianTokenizer.from_pretrained(self.model_name   )




	@property
	def      _UpperCamelCase       (					self   )						->				int:
			return self.tokenizer.eos_token_id




	@cached_property
	def      _UpperCamelCase       (					self   )						->				Tuple:
			lowerCamelCase	:     FlaxMarianMTModel            =       FlaxMarianMTModel.from_pretrained(self.model_name   )
			self.assertEqual(model.config.decoder_start_token_id						,					model.config.pad_token_id   )
			return model




	def      _UpperCamelCase       (					self						,					**UpperCAmelCase_   )						->				Union[str, Any]:
			lowerCamelCase	:     str            =       self.translate_src_text(**UpperCAmelCase_   )
			self.assertListEqual(self.expected_text						,					UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					**UpperCAmelCase_   )						->				int:
			lowerCamelCase	:     Any            =       self.tokenizer(self.src_text						,					padding=UpperCAmelCase_						,					return_tensors='np'						,					**UpperCAmelCase_   )
			lowerCamelCase	:     Any            =       self.model.generate(
			    model_inputs.input_ids						,					attention_mask=model_inputs.attention_mask						,					num_beams=2						,					max_length=128						,					).sequences
			lowerCamelCase	:     Any            =       self.tokenizer.batch_decode(UpperCAmelCase_						,					skip_special_tokens=UpperCAmelCase_   )
			return generated_words






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'en'
	lowercase_								=      'fr'
	lowercase_								=      [
	    'I am a small frog.',
	    'Now I can forget the 100 words of german that I know.',
	]
	lowercase_								=      [
	    'Je suis une petite grenouille.',
	    'Maintenant, je peux oublier les 100 mots d\'allemand que je connais.',
	]




	@slow
	def      _UpperCamelCase       (					self   )						->				int:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'fr'
	lowercase_								=      'en'
	lowercase_								=      [
	    'Donnez moi le micro.',
	    'Tom et Mary étaient assis à une table.',  # Accents
	]
	lowercase_								=      [
	    'Give me the microphone.',
	    'Tom and Mary were sitting at a table.',
	]




	@slow
	def      _UpperCamelCase       (					self   )						->				str:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'mt'
	lowercase_								=      'en'
	lowercase_								=      ['Billi messu b\'mod ġentili, Ġesù fejjaq raġel li kien milqut bil - marda kerha tal - ġdiem.']
	lowercase_								=      ['Touching gently, Jesus healed a man who was affected by the sad disease of leprosy.']




	@slow
	def      _UpperCamelCase       (					self   )						->				List[str]:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'en'
	lowercase_								=      'de'
	lowercase_								=      [
	    'I am a small frog.',
	    'Now I can forget the 100 words of german that I know.',
	    'Tom asked his teacher for advice.',
	    'That\'s how I would do it.',
	    'Tom really admired Mary\'s courage.',
	    'Turn around and close your eyes.',
	]
	lowercase_								=      [
	    'Ich bin ein kleiner Frosch.',
	    'Jetzt kann ich die 100 Wörter des Deutschen vergessen, die ich kenne.',
	    'Tom bat seinen Lehrer um Rat.',
	    'So würde ich das machen.',
	    'Tom bewunderte Marias Mut wirklich.',
	    'Drehen Sie sich um und schließen Sie die Augen.',
	]




	@slow
	def      _UpperCamelCase       (					self   )						->				Dict:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'en'
	lowercase_								=      'zh'
	lowercase_								=      ['My name is Wolfgang and I live in Berlin']
	lowercase_								=      ['我叫沃尔夫冈 我住在柏林']




	@slow
	def      _UpperCamelCase       (					self   )						->				Any:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'ru'
	lowercase_								=      'fr'
	lowercase_								=      ['Он показал мне рукопись своей новой пьесы.']
	lowercase_								=      ['Il m\'a montré le manuscrit de sa nouvelle pièce.']




	@slow
	def      _UpperCamelCase       (					self   )						->				Optional[Any]:
			self._assert_generated_batch_equal_expected()






@require_flax
@require_sentencepiece
@require_tokenizers
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'en'
	lowercase_								=      'ROMANCE'
	lowercase_								=      [
	    '>>fr<< Don\'t spend so much time watching TV.',
	    '>>pt<< Your message has been sent.',
	    '>>es<< He\'s two years older than me.',
	]
	lowercase_								=      [
	    'Ne passez pas autant de temps à regarder la télé.',
	    'A sua mensagem foi enviada.',
	    'Es dos años más viejo que yo.',
	]




	@slow
	def      _UpperCamelCase       (					self   )						->				str:
			self._assert_generated_batch_equal_expected()








"""simple docstring"""

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




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

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

							lowerCamelCase	:     Optional[int]            =       pd.DataFrame(tqa_pipeline_input['table']   )

			return tqa_pipeline_inputs






@add_end_docstrings(__UpperCAmelCase						)
class 			_lowercase  (							__UpperCAmelCase						):
	lowercase_								=      'table,query'




	def __init__(					self						,					UpperCAmelCase_=TableQuestionAnsweringArgumentHandler()						,					*UpperCAmelCase_						,					**UpperCAmelCase_   )						->				int:
			super().__init__(*UpperCAmelCase_						,					**UpperCAmelCase_   )
			lowerCamelCase	:     List[str]            =       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()   )   )

			lowerCamelCase	:     Dict            =       bool(getattr(self.model.config						,					'aggregation_labels'						,					UpperCAmelCase_   )   ) and bool(
			    getattr(self.model.config						,					'num_aggregation_labels'						,					UpperCAmelCase_   )   )
			lowerCamelCase	:     str            =       'tapas' if hasattr(self.model.config						,					'aggregation_labels'   ) else None




	def      _UpperCamelCase       (					self						,					**UpperCAmelCase_   )						->				Any:
			return self.model(**UpperCAmelCase_   )




	def      _UpperCamelCase       (					self						,					**UpperCAmelCase_   )						->				Dict:
			if self.framework == "pt":
					lowerCamelCase	:     List[Any]            =       []
					lowerCamelCase	:     Optional[Any]            =       []
					lowerCamelCase	:     List[str]            =       None
					lowerCamelCase	:     List[str]            =       inputs['input_ids'].shape[0]

					lowerCamelCase	:     Any            =       inputs['input_ids'].to(self.device   )
					lowerCamelCase	:     Optional[Any]            =       inputs['attention_mask'].to(self.device   )
					lowerCamelCase	:     Optional[int]            =       inputs['token_type_ids'].to(self.device   )
					lowerCamelCase	:     str            =       None

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

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

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

									lowerCamelCase	:     Optional[int]            =       torch.from_numpy(UpperCAmelCase_   ).type(torch.long   ).to(self.device   )

							lowerCamelCase	:     List[Any]            =       input_ids[index]
							lowerCamelCase	:     Optional[int]            =       attention_mask[index]  # shape (seq_len,)
							lowerCamelCase	:     List[str]            =       token_type_ids[index]  # shape (seq_len, 7)
							lowerCamelCase	:     Tuple            =       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   )						,					)
							lowerCamelCase	:     str            =       outputs.logits

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

							all_logits.append(UpperCAmelCase_   )

							lowerCamelCase	:     Dict            =       torch.distributions.Bernoulli(logits=UpperCAmelCase_   )
							lowerCamelCase	:     Tuple            =       dist_per_token.probs * attention_mask_example.type(torch.floataa   ).to(
							    dist_per_token.probs.device   )

							lowerCamelCase	:     str            =       collections.defaultdict(UpperCAmelCase_   )
							for i, p in enumerate(probabilities.squeeze().tolist()   ):
									lowerCamelCase	:     Tuple            =       token_type_ids_example[:, 0].tolist()[i]
									lowerCamelCase	:     Dict            =       token_type_ids_example[:, 1].tolist()[i] - 1
									lowerCamelCase	:     List[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(UpperCAmelCase_   )

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

					lowerCamelCase	:     int            =       torch.cat(tuple(UpperCAmelCase_   )						,					0   )

					return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(UpperCAmelCase_   )						,					0   ))
			else:
					lowerCamelCase	:     Union[str, Any]            =       []
					lowerCamelCase	:     Union[str, Any]            =       []
					lowerCamelCase	:     Union[str, Any]            =       None
					lowerCamelCase	:     str            =       inputs['input_ids'].shape[0]

					lowerCamelCase	:     List[Any]            =       inputs['input_ids']
					lowerCamelCase	:     str            =       inputs['attention_mask']
					lowerCamelCase	:     Optional[Any]            =       inputs['token_type_ids'].numpy()
					lowerCamelCase	:     Optional[Any]            =       None

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

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

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

									lowerCamelCase	:     Optional[int]            =       model_labels

							lowerCamelCase	:     str            =       input_ids[index]
							lowerCamelCase	:     Tuple            =       attention_mask[index]  # shape (seq_len,)
							lowerCamelCase	:     Tuple            =       token_type_ids[index]  # shape (seq_len, 7)
							lowerCamelCase	:     Union[str, Any]            =       self.model(
							    input_ids=np.expand_dims(UpperCAmelCase_						,					axis=0   )						,					attention_mask=np.expand_dims(UpperCAmelCase_						,					axis=0   )						,					token_type_ids=np.expand_dims(UpperCAmelCase_						,					axis=0   )						,					)
							lowerCamelCase	:     int            =       outputs.logits

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

							all_logits.append(UpperCAmelCase_   )

							lowerCamelCase	:     int            =       tfp.distributions.Bernoulli(logits=UpperCAmelCase_   )
							lowerCamelCase	:     Dict            =       dist_per_token.probs_parameter() * tf.cast(UpperCAmelCase_						,					tf.floataa   )

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

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

					lowerCamelCase	:     Union[str, Any]            =       tf.concat(tuple(UpperCAmelCase_   )						,					0   )

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




	def __call__(					self						,					*UpperCAmelCase_						,					**UpperCAmelCase_   )						->				Optional[int]:
			lowerCamelCase	:     Optional[Any]            =       self._args_parser(*UpperCAmelCase_						,					**UpperCAmelCase_   )

			lowerCamelCase	:     Union[str, Any]            =       super().__call__(UpperCAmelCase_						,					**UpperCAmelCase_   )
			if len(UpperCAmelCase_   ) == 1:
					return results[0]
			return results




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_=None						,					UpperCAmelCase_=None						,					UpperCAmelCase_=None						,					**UpperCAmelCase_   )						->				Union[str, Any]:
			lowerCamelCase	:     List[Any]            =       {}
			if padding is not None:
					lowerCamelCase	:     Union[str, Any]            =       padding
			if truncation is not None:
					lowerCamelCase	:     Dict            =       truncation

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




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_=None						,					UpperCAmelCase_=True						,					UpperCAmelCase_=None   )						->				str:
			if truncation is None:
					if self.type == "tapas":
							lowerCamelCase	:     Any            =       'drop_rows_to_fit'
					else:
							lowerCamelCase	:     str            =       'do_not_truncate'

			lowerCamelCase      ,       lowerCamelCase	:     List[str]            =       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'   )
			lowerCamelCase	:     Union[str, Any]            =       self.tokenizer(UpperCAmelCase_						,					UpperCAmelCase_						,					return_tensors=self.framework						,					truncation=UpperCAmelCase_						,					padding=UpperCAmelCase_   )
			lowerCamelCase	:     int            =       table
			return inputs




	def      _UpperCamelCase       (					self						,					UpperCAmelCase_						,					UpperCAmelCase_=False   )						->				Optional[Any]:
			lowerCamelCase	:     Optional[Any]            =       model_inputs.pop('table'   )

			if self.type == "tapas":
					if sequential:
							lowerCamelCase	:     List[Any]            =       self.sequential_inference(**UpperCAmelCase_   )
					else:
							lowerCamelCase	:     int            =       self.batch_inference(**UpperCAmelCase_   )
			else:
					lowerCamelCase	:     Tuple            =       self.model.generate(**UpperCAmelCase_   )
			lowerCamelCase	:     Union[str, Any]            =       {'model_inputs': model_inputs, 'table': table, 'outputs': outputs}
			return model_outputs




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

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

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

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






