code: 
  
  
  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 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
  
  
  
  
       def __call__( self       :       int	,      UpperCamelCase       :       List[Any]=None	,      UpperCamelCase       :       List[str]=None	,      **UpperCamelCase       :       int		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              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:
                            _lowercase					:				List[str]           =			[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:
                                   _lowercase					:				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:
                     _lowercase					:				Union[str, 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.'''		)
  
                            _lowercase					:				str           =			pd.DataFrame(tqa_pipeline_input['''table''']		)
  
              return tqa_pipeline_inputs
  
  
  
  
  @add_end_docstrings(A_		)
  class 						UpperCAmelCase__   (      A_		):
  
  
  
       '''simple docstring'''
       UpperCAmelCase_         =  '''table,query'''
  
  
  
  
       def __init__( self       :       Optional[int]	,      UpperCamelCase       :       Optional[Any]=TableQuestionAnsweringArgumentHandler()	,      *UpperCamelCase       :       Any	,      **UpperCamelCase       :       int		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              super().__init__(*UpperCamelCase	,      **UpperCamelCase		)
              _lowercase					:				Dict           =			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()		)		)
  
              _lowercase					:				Dict           =			bool(getattr(self.model.config	,      '''aggregation_labels'''	,      UpperCamelCase		)		) and bool(
                  getattr(self.model.config	,      '''num_aggregation_labels'''	,      UpperCamelCase		)		)
              _lowercase					:				Optional[Any]           =			'''tapas''' if hasattr(self.model.config	,      '''aggregation_labels'''		) else None
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[Any]	,      **UpperCamelCase       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              return self.model(**UpperCamelCase		)
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Optional[int]	,      **UpperCamelCase       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              if self.framework == "pt":
                     _lowercase					:				Union[str, Any]           =			[]
                     _lowercase					:				Union[str, Any]           =			[]
                     _lowercase					:				str           =			None
                     _lowercase					:				List[str]           =			inputs['''input_ids'''].shape[0]
  
                     _lowercase					:				Dict           =			inputs['''input_ids'''].to(self.device		)
                     _lowercase					:				int           =			inputs['''attention_mask'''].to(self.device		)
                     _lowercase					:				int           =			inputs['''token_type_ids'''].to(self.device		)
                     _lowercase					:				List[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:
                                   _lowercase					:				List[str]           =			token_type_ids_example[:, 3]  # shape (seq_len,)
                                   _lowercase					:				List[str]           =			np.zeros_like(prev_labels_example.cpu().numpy()		)  # shape (seq_len,)
  
                                   _lowercase					:				str           =			token_type_ids[index]  # shape (seq_len, 7)
                                   for i in range(model_labels.shape[0]		):
                                          _lowercase					:				Union[str, Any]           =			token_type_ids_example[:, 0].tolist()[i]
                                          _lowercase					:				List[Any]           =			token_type_ids_example[:, 1].tolist()[i] - 1
                                          _lowercase					:				Dict           =			token_type_ids_example[:, 2].tolist()[i] - 1
  
                                          if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                                 _lowercase					:				int           =			int(prev_answers[(col_id, row_id)]		)
  
                                   _lowercase					:				Tuple           =			torch.from_numpy(UpperCamelCase		).type(torch.long		).to(self.device		)
  
                            _lowercase					:				int           =			input_ids[index]
                            _lowercase					:				Tuple           =			attention_mask[index]  # shape (seq_len,)
                            _lowercase					:				List[str]           =			token_type_ids[index]  # shape (seq_len, 7)
                            _lowercase					:				List[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		)	,      )
                            _lowercase					:				Any           =			outputs.logits
  
                            if self.aggregate:
                                   all_aggregations.append(outputs.logits_aggregation		)
  
                            all_logits.append(UpperCamelCase		)
  
                            _lowercase					:				List[Any]           =			torch.distributions.Bernoulli(logits=UpperCamelCase		)
                            _lowercase					:				Optional[int]           =			dist_per_token.probs * attention_mask_example.type(torch.floataa		).to(
                                dist_per_token.probs.device		)
  
                            _lowercase					:				Union[str, Any]           =			collections.defaultdict(UpperCamelCase		)
                            for i, p in enumerate(probabilities.squeeze().tolist()		):
                                   _lowercase					:				Optional[Any]           =			token_type_ids_example[:, 0].tolist()[i]
                                   _lowercase					:				Dict           =			token_type_ids_example[:, 1].tolist()[i] - 1
                                   _lowercase					:				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		)
  
                            _lowercase					:				List[str]           =			{key: np.array(coords_to_probs[key]		).mean() > 0.5 for key in coords_to_probs}
  
                     _lowercase					:				Optional[int]           =			torch.cat(tuple(UpperCamelCase		)	,      0		)
  
                     return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(UpperCamelCase		)	,      0		))
              else:
                     _lowercase					:				Optional[Any]           =			[]
                     _lowercase					:				Tuple           =			[]
                     _lowercase					:				Optional[int]           =			None
                     _lowercase					:				str           =			inputs['''input_ids'''].shape[0]
  
                     _lowercase					:				List[Any]           =			inputs['''input_ids''']
                     _lowercase					:				List[str]           =			inputs['''attention_mask''']
                     _lowercase					:				List[str]           =			inputs['''token_type_ids'''].numpy()
                     _lowercase					:				Tuple           =			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:
                                   _lowercase					:				Any           =			token_type_ids_example[:, 3]  # shape (seq_len,)
                                   _lowercase					:				Union[str, Any]           =			np.zeros_like(UpperCamelCase	,      dtype=np.intaa		)  # shape (seq_len,)
  
                                   _lowercase					:				Union[str, Any]           =			token_type_ids[index]  # shape (seq_len, 7)
                                   for i in range(model_labels.shape[0]		):
                                          _lowercase					:				Optional[int]           =			token_type_ids_example[:, 0].tolist()[i]
                                          _lowercase					:				str           =			token_type_ids_example[:, 1].tolist()[i] - 1
                                          _lowercase					:				Optional[Any]           =			token_type_ids_example[:, 2].tolist()[i] - 1
  
                                          if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                                 _lowercase					:				Tuple           =			int(prev_answers[(col_id, row_id)]		)
  
                                   _lowercase					:				Dict           =			model_labels
  
                            _lowercase					:				int           =			input_ids[index]
                            _lowercase					:				List[str]           =			attention_mask[index]  # shape (seq_len,)
                            _lowercase					:				str           =			token_type_ids[index]  # shape (seq_len, 7)
                            _lowercase					:				List[str]           =			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		)	,      )
                            _lowercase					:				List[Any]           =			outputs.logits
  
                            if self.aggregate:
                                   all_aggregations.append(outputs.logits_aggregation		)
  
                            all_logits.append(UpperCamelCase		)
  
                            _lowercase					:				Union[str, Any]           =			tfp.distributions.Bernoulli(logits=UpperCamelCase		)
                            _lowercase					:				Any           =			dist_per_token.probs_parameter() * tf.cast(UpperCamelCase	,      tf.floataa		)
  
                            _lowercase					:				str           =			collections.defaultdict(UpperCamelCase		)
                            _lowercase					:				Dict           =			token_type_ids_example
                            for i, p in enumerate(tf.squeeze(UpperCamelCase		).numpy().tolist()		):
                                   _lowercase					:				Tuple           =			token_type_ids_example[:, 0].tolist()[i]
                                   _lowercase					:				Optional[int]           =			token_type_ids_example[:, 1].tolist()[i] - 1
                                   _lowercase					:				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		)
  
                            _lowercase					:				Optional[int]           =			{key: np.array(coords_to_probs[key]		).mean() > 0.5 for key in coords_to_probs}
  
                     _lowercase					:				List[Any]           =			tf.concat(tuple(UpperCamelCase		)	,      0		)
  
                     return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(UpperCamelCase		)	,      0		))
  
  
  
  
       def __call__( self       :       Optional[Any]	,      *UpperCamelCase       :       str	,      **UpperCamelCase       :       Tuple		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				List[Any]           =			self._args_parser(*UpperCamelCase	,      **UpperCamelCase		)
  
              _lowercase					:				Dict           =			super().__call__(UpperCamelCase	,      **UpperCamelCase		)
              if len(UpperCamelCase		) == 1:
                     return results[0]
              return results
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Any	,      UpperCamelCase       :       Tuple=None	,      UpperCamelCase       :       List[Any]=None	,      UpperCamelCase       :       Tuple=None	,      **UpperCamelCase       :       int		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[Any]           =			{}
              if padding is not None:
                     _lowercase					:				Dict           =			padding
              if truncation is not None:
                     _lowercase					:				List[str]           =			truncation
  
              _lowercase					:				Tuple           =			{}
              if sequential is not None:
                     _lowercase					:				int           =			sequential
              return preprocess_params, forward_params, {}
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Any	,      UpperCamelCase       :       int	,      UpperCamelCase       :       Dict=None	,      UpperCamelCase       :       List[str]=True	,      UpperCamelCase       :       str=None		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              if truncation is None:
                     if self.type == "tapas":
                            _lowercase					:				Optional[int]           =			'''drop_rows_to_fit'''
                     else:
                            _lowercase					:				int           =			'''do_not_truncate'''
  
              _lowercase       ,	_lowercase					:				Dict           =			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'''		)
              _lowercase					:				Optional[int]           =			self.tokenizer(UpperCamelCase	,      UpperCamelCase	,      return_tensors=self.framework	,      truncation=UpperCamelCase	,      padding=UpperCamelCase		)
              _lowercase					:				str           =			table
              return inputs
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Dict	,      UpperCamelCase       :       Tuple	,      UpperCamelCase       :       Union[str, Any]=False		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Optional[int]           =			model_inputs.pop('''table'''		)
  
              if self.type == "tapas":
                     if sequential:
                            _lowercase					:				List[str]           =			self.sequential_inference(**UpperCamelCase		)
                     else:
                            _lowercase					:				Union[str, Any]           =			self.batch_inference(**UpperCamelCase		)
              else:
                     _lowercase					:				List[str]           =			self.model.generate(**UpperCamelCase		)
              _lowercase					:				int           =			{'''model_inputs''': model_inputs, '''table''': table, '''outputs''': outputs}
              return model_outputs
  
  
  
  
       def   lowerCAmelCase_   ( self       :       Any	,      UpperCamelCase       :       List[Any]		):
  
  
  
  
  
              """simple docstring"""
  
  
  
              _lowercase					:				Union[str, Any]           =			model_outputs['''model_inputs''']
              _lowercase					:				Optional[Any]           =			model_outputs['''table''']
              _lowercase					:				Any           =			model_outputs['''outputs''']
              if self.type == "tapas":
                     if self.aggregate:
                            _lowercase       ,	_lowercase					:				Optional[int]           =			outputs[:2]
                            _lowercase					:				Tuple           =			self.tokenizer.convert_logits_to_predictions(UpperCamelCase	,      UpperCamelCase	,      UpperCamelCase		)
                            _lowercase       ,	_lowercase					:				int           =			predictions
                            _lowercase					:				Tuple           =			{i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(UpperCamelCase		)}
  
                            _lowercase					:				Union[str, Any]           =			self.model.config.no_aggregation_label_index
                            _lowercase					:				str           =			{
                                i: aggregators[i] + ''' > ''' for i, pred in enumerate(UpperCamelCase		) if pred != no_agg_label_index
                            }
                     else:
                            _lowercase					:				Optional[int]           =			outputs[0]
                            _lowercase					:				Optional[Any]           =			self.tokenizer.convert_logits_to_predictions(UpperCamelCase	,      UpperCamelCase		)
                            _lowercase					:				List[str]           =			predictions[0]
                            _lowercase					:				Dict           =			{}
                            _lowercase					:				Optional[int]           =			{}
                     _lowercase					:				List[str]           =			[]
                     for index, coordinates in enumerate(UpperCamelCase		):
                            _lowercase					:				int           =			[table.iat[coordinate] for coordinate in coordinates]
                            _lowercase					:				List[str]           =			aggregators.get(UpperCamelCase	,      ''''''		)
                            _lowercase					:				Union[str, Any]           =			aggregators_prefix.get(UpperCamelCase	,      ''''''		)
                            _lowercase					:				List[str]           =			{
                                '''answer''': aggregator_prefix + ''', '''.join(UpperCamelCase		),
                                '''coordinates''': coordinates,
                                '''cells''': [table.iat[coordinate] for coordinate in coordinates],
                            }
                            if aggregator:
                                   _lowercase					:				Any           =			aggregator
  
                            answers.append(UpperCamelCase		)
                     if len(UpperCamelCase		) == 0:
                            raise PipelineException('''Empty answer'''		)
              else:
                     _lowercase					:				Union[str, Any]           =			[{'''answer''': answer} for answer in self.tokenizer.batch_decode(UpperCamelCase	,      skip_special_tokens=UpperCamelCase		)]
  
              return answers if len(UpperCamelCase		) > 1 else answers[0]
style_context: 
  
  
  from typing import TYPE_CHECKING
  
  from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
  
  
  UpperCamelCase__				       =			{
      'configuration_wav2vec2_conformer': [
          'WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP',
          'Wav2Vec2ConformerConfig',
      ],
  }
  
  
  try:
     if not is_torch_available():
        raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
     pass
  else:
     UpperCamelCase__				       =			[
         'WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST',
         'Wav2Vec2ConformerForAudioFrameClassification',
         'Wav2Vec2ConformerForCTC',
         'Wav2Vec2ConformerForPreTraining',
         'Wav2Vec2ConformerForSequenceClassification',
         'Wav2Vec2ConformerForXVector',
         'Wav2Vec2ConformerModel',
         'Wav2Vec2ConformerPreTrainedModel',
     ]
  
  if TYPE_CHECKING:
     from .configuration_wavaveca_conformer import (
         WAV2VEC2_CONFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
         WavaVecaConformerConfig,
     )
  
     try:
        if not is_torch_available():
           raise OptionalDependencyNotAvailable()
     except OptionalDependencyNotAvailable:
        pass
     else:
        from .modeling_wavaveca_conformer import (
            WAV2VEC2_CONFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
            WavaVecaConformerForAudioFrameClassification,
            WavaVecaConformerForCTC,
            WavaVecaConformerForPreTraining,
            WavaVecaConformerForSequenceClassification,
            WavaVecaConformerForXVector,
            WavaVecaConformerModel,
            WavaVecaConformerPreTrainedModel,
        )
  
  else:
     import sys
  
     UpperCamelCase__				       =			_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)