code: 
  
  
  
  
  
  
  """simple docstring"""
  
  import glob
  import os
  from typing import Dict, List, Union
  
  import torch
  
  from diffusers.utils import is_safetensors_available
  
  
  if is_safetensors_available():
  					import safetensors.torch
  
  from huggingface_hub import snapshot_download
  
  from diffusers import DiffusionPipeline, __version__
  from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
  from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME
  
  
  class 	__lowerCamelCase       (				A__    ):
  
  
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  		def __init__(     self							:			Optional[Any]			):
  				self.register_to_config()
  				super().__init__()
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Optional[Any]		,    a_							:			Union[str, Any]		,    a_							:			Optional[Any]			):
  				if dicta == dicta:
  						return True
  				else:
  						lowerCAmelCase_       ,			lowerCAmelCase_     :							Optional[int]             =    self._remove_meta_keys(a_			)
  						lowerCAmelCase_       ,			lowerCAmelCase_     :							int             =    self._remove_meta_keys(a_			)
  						if configa == configa:
  								print(f'''Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'''			)
  								return True
  				return False
  
  
  
  
  
  		def      lowerCamelCase (     self							:			List[str]		,    a_							:			Dict			):
  				lowerCAmelCase_     :							Any             =    []
  				lowerCAmelCase_     :							Optional[int]             =    config_dict.copy()
  				for key in config_dict.keys():
  						if key.startswith("_"			):
  								temp_dict.pop(a_			)
  								meta_keys.append(a_			)
  				return (temp_dict, meta_keys)
  
  
  
  
  
  		@torch.no_grad()
  		def      lowerCamelCase (     self							:			Optional[Any]		,    a_							:			List[Union[str, os.PathLike]]		,    **a_							:			Optional[int]			):
  				lowerCAmelCase_     :							str             =    kwargs.pop("cache_dir"		,    a_			)
  				lowerCAmelCase_     :							List[str]             =    kwargs.pop("resume_download"		,    a_			)
  				lowerCAmelCase_     :							Dict             =    kwargs.pop("force_download"		,    a_			)
  				lowerCAmelCase_     :							str             =    kwargs.pop("proxies"		,    a_			)
  				lowerCAmelCase_     :							str             =    kwargs.pop("local_files_only"		,    a_			)
  				lowerCAmelCase_     :							List[str]             =    kwargs.pop("use_auth_token"		,    a_			)
  				lowerCAmelCase_     :							Optional[Any]             =    kwargs.pop("revision"		,    a_			)
  				lowerCAmelCase_     :							List[str]             =    kwargs.pop("torch_dtype"		,    a_			)
  				lowerCAmelCase_     :							Any             =    kwargs.pop("device_map"		,    a_			)
  
  				lowerCAmelCase_     :							Any             =    kwargs.pop("alpha"		,    0.5			)
  				lowerCAmelCase_     :							Dict             =    kwargs.pop("interp"		,    a_			)
  
  				print("Received list"		,    a_			)
  				print(f'''Combining with alpha={alpha}, interpolation mode={interp}'''			)
  
  				lowerCAmelCase_     :							Tuple             =    len(a_			)
  				# Ignore result from model_index_json comparision of the two checkpoints
  				lowerCAmelCase_     :							List[str]             =    kwargs.pop("force"		,    a_			)
  
  				# If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
  				if checkpoint_count > 3 or checkpoint_count < 2:
  						raise ValueError(
  						    "Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being"
  						    " passed."			)
  
  				print("Received the right number of checkpoints"			)
  				# chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
  				# chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None
  
  				# Validate that the checkpoints can be merged
  				# Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
  				lowerCAmelCase_     :							str             =    []
  				for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
  						lowerCAmelCase_     :							int             =    DiffusionPipeline.load_config(
  						    a_		,    cache_dir=a_		,    resume_download=a_		,    force_download=a_		,    proxies=a_		,    local_files_only=a_		,    use_auth_token=a_		,    revision=a_		,    )
  						config_dicts.append(a_			)
  
  				lowerCAmelCase_     :							List[Any]             =    True
  				for idx in range(1		,    len(a_			)			):
  						comparison_result &= self._compare_model_configs(config_dicts[idx - 1]		,    config_dicts[idx]			)
  						if not force and comparison_result is False:
  								raise ValueError("Incompatible checkpoints. Please check model_index.json for the models."			)
  								print(config_dicts[0]		,    config_dicts[1]			)
  				print("Compatible model_index.json files found"			)
  				# Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
  				lowerCAmelCase_     :							Dict             =    []
  				for pretrained_model_name_or_path, config_dict in zip(a_		,    a_			):
  						lowerCAmelCase_     :							Optional[int]             =    [k for k in config_dict.keys() if not k.startswith("_"			)]
  						lowerCAmelCase_     :							Dict             =    [os.path.join(a_		,    "*"			) for k in folder_names]
  						allow_patterns += [
  						    WEIGHTS_NAME,
  						    SCHEDULER_CONFIG_NAME,
  						    CONFIG_NAME,
  						    ONNX_WEIGHTS_NAME,
  						    DiffusionPipeline.config_name,
  						]
  						lowerCAmelCase_     :							int             =    config_dict.get("_class_name"			)
  						lowerCAmelCase_     :							List[str]             =    {"diffusers": __version__, "pipeline_class": requested_pipeline_class}
  
  						lowerCAmelCase_     :							List[str]             =    (
  						    pretrained_model_name_or_path
  						    if os.path.isdir(a_			)
  						    else snapshot_download(
  						        a_		,    cache_dir=a_		,    resume_download=a_		,    proxies=a_		,    local_files_only=a_		,    use_auth_token=a_		,    revision=a_		,    allow_patterns=a_		,    user_agent=a_		,    )
  						)
  						print("Cached Folder"		,    a_			)
  						cached_folders.append(a_			)
  
  				# Step 3:-
  				# Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
  				lowerCAmelCase_     :							str             =    DiffusionPipeline.from_pretrained(
  				    cached_folders[0]		,    torch_dtype=a_		,    device_map=a_			)
  				final_pipe.to(self.device			)
  
  				lowerCAmelCase_     :							List[Any]             =    None
  				if len(a_			) > 2:
  						lowerCAmelCase_     :							List[Any]             =    os.path.join(cached_folders[2]			)
  
  				if interp == "sigmoid":
  						lowerCAmelCase_     :							Optional[int]             =    CheckpointMergerPipeline.sigmoid
  				elif interp == "inv_sigmoid":
  						lowerCAmelCase_     :							str             =    CheckpointMergerPipeline.inv_sigmoid
  				elif interp == "add_diff":
  						lowerCAmelCase_     :							Optional[Any]             =    CheckpointMergerPipeline.add_difference
  				else:
  						lowerCAmelCase_     :							Optional[Any]             =    CheckpointMergerPipeline.weighted_sum
  
  				# Find each module's state dict.
  				for attr in final_pipe.config.keys():
  						if not attr.startswith("_"			):
  								lowerCAmelCase_     :							Optional[Any]             =    os.path.join(cached_folders[1]		,    a_			)
  								if os.path.exists(a_			):
  										lowerCAmelCase_     :							Any             =    [
  										    *glob.glob(os.path.join(a_		,    "*.safetensors"			)			),
  										    *glob.glob(os.path.join(a_		,    "*.bin"			)			),
  										]
  										lowerCAmelCase_     :							Optional[int]             =    files[0] if len(a_			) > 0 else None
  								if len(a_			) < 3:
  										lowerCAmelCase_     :							Any             =    None
  								else:
  										lowerCAmelCase_     :							List[str]             =    os.path.join(cached_folders[2]		,    a_			)
  										if os.path.exists(a_			):
  												lowerCAmelCase_     :							Dict             =    [
  												    *glob.glob(os.path.join(a_		,    "*.safetensors"			)			),
  												    *glob.glob(os.path.join(a_		,    "*.bin"			)			),
  												]
  												lowerCAmelCase_     :							List[Any]             =    files[0] if len(a_			) > 0 else None
                  # For an attr if both checkpoint_path_1 and 2 are None, ignore.
                  # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
  								if checkpoint_path_a is None and checkpoint_path_a is None:
  										print(f'''Skipping {attr}: not present in 2nd or 3d model'''			)
  										continue
  								try:
  										lowerCAmelCase_     :							str             =    getattr(a_		,    a_			)
  										if isinstance(a_		,    a_			):  # ignore requires_safety_checker boolean
  												continue
  										lowerCAmelCase_     :							List[str]             =    getattr(a_		,    "state_dict"			)
  										lowerCAmelCase_     :							str             =    theta_a()
  
  										lowerCAmelCase_     :							Any             =    getattr(a_		,    "load_state_dict"			)
  										lowerCAmelCase_     :							Tuple             =    (
  										    safetensors.torch.load_file(a_			)
  										    if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"			))
  										    else torch.load(a_		,    map_location="cpu"			)
  										)
  										lowerCAmelCase_     :							List[str]             =    None
  										if checkpoint_path_a:
  												lowerCAmelCase_     :							Tuple             =    (
  												    safetensors.torch.load_file(a_			)
  												    if (is_safetensors_available() and checkpoint_path_a.endswith(".safetensors"			))
  												    else torch.load(a_		,    map_location="cpu"			)
  												)
  
  										if not theta_a.keys() == theta_a.keys():
  												print(f'''Skipping {attr}: key mismatch'''			)
  												continue
  										if theta_a and not theta_a.keys() == theta_a.keys():
  												print(f'''Skipping {attr}:y mismatch'''			)
  								except Exception as e:
  										print(f'''Skipping {attr} do to an unexpected error: {str(a_			)}'''			)
  										continue
  								print(f'''MERGING {attr}'''			)
  
  								for key in theta_a.keys():
  										if theta_a:
  												lowerCAmelCase_     :							Union[str, Any]             =    theta_func(theta_a[key]		,    theta_a[key]		,    theta_a[key]		,    a_			)
  										else:
  												lowerCAmelCase_     :							Optional[Any]             =    theta_func(theta_a[key]		,    theta_a[key]		,    a_		,    a_			)
  
  								del theta_a
  								del theta_a
  								update_theta_a(a_			)
  
  								del theta_a
  				return final_pipe
  
  
  
  
  
  		@staticmethod
  		def      lowerCamelCase (     a_							:			str		,    a_							:			Optional[Any]		,    a_							:			Any		,    a_							:			Optional[Any]			):
  				return ((1 - alpha) * thetaa) + (alpha * thetaa)
  
  
  
  
  
  		@staticmethod
  		def      lowerCamelCase (     a_							:			Any		,    a_							:			Union[str, Any]		,    a_							:			Any		,    a_							:			Union[str, Any]			):
  				lowerCAmelCase_     :							Optional[int]             =    alpha * alpha * (3 - (2 * alpha))
  				return thetaa + ((thetaa - thetaa) * alpha)
  
  
  
  
  
  		@staticmethod
  		def      lowerCamelCase (     a_							:			str		,    a_							:			Optional[Any]		,    a_							:			Optional[Any]		,    a_							:			int			):
  				import math
  
  				lowerCAmelCase_     :							str             =    0.5 - math.sin(math.asin(1.0 - 2.0 * alpha			) / 3.0			)
  				return thetaa + ((thetaa - thetaa) * alpha)
  
  
  
  
  
  		@staticmethod
  		def      lowerCamelCase (     a_							:			Optional[Any]		,    a_							:			Union[str, Any]		,    a_							:			List[str]		,    a_							:			Dict			):
  				return thetaa + (thetaa - thetaa) * (1.0 - alpha)
  
style_context: 
  
  
  
  
  
  
  """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 	__lowerCamelCase       (				A__    ):
  
  
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  		def __call__(     self							:			Any		,    a_							:			Any=None		,    a_							:			List[Any]=None		,    **a_							:			Optional[int]			):
  				# 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:
  								lowerCAmelCase_     :							Any             =    [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:
  										lowerCAmelCase_     :							Dict             =    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:
  						lowerCAmelCase_     :							Tuple             =    [{"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(A__    )
  class 	__lowerCamelCase       (				A__    ):
  
  
  
  
  
  		'''simple docstring'''
  
  
  
  
  
  
  		a_			:       str      =							"""table,query"""
  
  
  
  
  
  		def __init__(     self							:			str		,    a_							:			Optional[Any]=TableQuestionAnsweringArgumentHandler()		,    *a_							:			List[Any]		,    **a_							:			Union[str, Any]			):
  				super().__init__(*a_		,    **a_			)
  				lowerCAmelCase_     :							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()			)			)
  
  				lowerCAmelCase_     :							Any             =    bool(getattr(self.model.config		,    "aggregation_labels"		,    a_			)			) and bool(
  				    getattr(self.model.config		,    "num_aggregation_labels"		,    a_			)			)
  				lowerCAmelCase_     :							List[Any]             =    "tapas" if hasattr(self.model.config		,    "aggregation_labels"			) else None
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Optional[Any]		,    **a_							:			Union[str, Any]			):
  				return self.model(**a_			)
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Optional[Any]		,    **a_							:			Union[str, Any]			):
  				if self.framework == "pt":
  						lowerCAmelCase_     :							Optional[int]             =    []
  						lowerCAmelCase_     :							str             =    []
  						lowerCAmelCase_     :							str             =    None
  						lowerCAmelCase_     :							Union[str, Any]             =    inputs["input_ids"].shape[0]
  
  						lowerCAmelCase_     :							Dict             =    inputs["input_ids"].to(self.device			)
  						lowerCAmelCase_     :							Dict             =    inputs["attention_mask"].to(self.device			)
  						lowerCAmelCase_     :							List[str]             =    inputs["token_type_ids"].to(self.device			)
  						lowerCAmelCase_     :							Optional[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:
  										lowerCAmelCase_     :							Union[str, Any]             =    token_type_ids_example[:, 3]  # shape (seq_len,)
  										lowerCAmelCase_     :							int             =    np.zeros_like(prev_labels_example.cpu().numpy()			)  # shape (seq_len,)
  
  										lowerCAmelCase_     :							Union[str, Any]             =    token_type_ids[index]  # shape (seq_len, 7)
  										for i in range(model_labels.shape[0]			):
  												lowerCAmelCase_     :							List[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_     :							List[Any]             =    torch.from_numpy(a_			).type(torch.long			).to(self.device			)
  
  								lowerCAmelCase_     :							int             =    input_ids[index]
  								lowerCAmelCase_     :							Optional[int]             =    attention_mask[index]  # shape (seq_len,)
  								lowerCAmelCase_     :							Union[str, Any]             =    token_type_ids[index]  # shape (seq_len, 7)
  								lowerCAmelCase_     :							int             =    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_     :							Optional[Any]             =    outputs.logits
  
  								if self.aggregate:
  										all_aggregations.append(outputs.logits_aggregation			)
  
  								all_logits.append(a_			)
  
  								lowerCAmelCase_     :							str             =    torch.distributions.Bernoulli(logits=a_			)
  								lowerCAmelCase_     :							List[Any]             =    dist_per_token.probs * attention_mask_example.type(torch.floataa			).to(
  								    dist_per_token.probs.device			)
  
  								lowerCAmelCase_     :							Optional[Any]             =    collections.defaultdict(a_			)
  								for i, p in enumerate(probabilities.squeeze().tolist()			):
  										lowerCAmelCase_     :							List[Any]             =    token_type_ids_example[:, 0].tolist()[i]
  										lowerCAmelCase_     :							List[str]             =    token_type_ids_example[:, 1].tolist()[i] - 1
  										lowerCAmelCase_     :							List[str]             =    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_			)
  
  								lowerCAmelCase_     :							List[Any]             =    {key: np.array(coords_to_probs[key]			).mean() > 0.5 for key in coords_to_probs}
  
  						lowerCAmelCase_     :							Optional[Any]             =    torch.cat(tuple(a_			)		,    0			)
  
  						return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(a_			)		,    0			))
  				else:
  						lowerCAmelCase_     :							str             =    []
  						lowerCAmelCase_     :							List[str]             =    []
  						lowerCAmelCase_     :							str             =    None
  						lowerCAmelCase_     :							List[Any]             =    inputs["input_ids"].shape[0]
  
  						lowerCAmelCase_     :							Tuple             =    inputs["input_ids"]
  						lowerCAmelCase_     :							Optional[int]             =    inputs["attention_mask"]
  						lowerCAmelCase_     :							Dict             =    inputs["token_type_ids"].numpy()
  						lowerCAmelCase_     :							Optional[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:
  										lowerCAmelCase_     :							Dict             =    token_type_ids_example[:, 3]  # shape (seq_len,)
  										lowerCAmelCase_     :							Tuple             =    np.zeros_like(a_		,    dtype=np.intaa			)  # shape (seq_len,)
  
  										lowerCAmelCase_     :							List[str]             =    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_     :							Tuple             =    token_type_ids_example[:, 1].tolist()[i] - 1
  												lowerCAmelCase_     :							Dict             =    token_type_ids_example[:, 2].tolist()[i] - 1
  
  												if row_id >= 0 and col_id >= 0 and segment_id == 1:
  														lowerCAmelCase_     :							Union[str, Any]             =    int(prev_answers[(col_id, row_id)]			)
  
  										lowerCAmelCase_     :							str             =    model_labels
  
  								lowerCAmelCase_     :							Union[str, Any]             =    input_ids[index]
  								lowerCAmelCase_     :							int             =    attention_mask[index]  # shape (seq_len,)
  								lowerCAmelCase_     :							Optional[int]             =    token_type_ids[index]  # shape (seq_len, 7)
  								lowerCAmelCase_     :							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			)		,    )
  								lowerCAmelCase_     :							str             =    outputs.logits
  
  								if self.aggregate:
  										all_aggregations.append(outputs.logits_aggregation			)
  
  								all_logits.append(a_			)
  
  								lowerCAmelCase_     :							Optional[int]             =    tfp.distributions.Bernoulli(logits=a_			)
  								lowerCAmelCase_     :							Any             =    dist_per_token.probs_parameter() * tf.cast(a_		,    tf.floataa			)
  
  								lowerCAmelCase_     :							Dict             =    collections.defaultdict(a_			)
  								lowerCAmelCase_     :							Optional[int]             =    token_type_ids_example
  								for i, p in enumerate(tf.squeeze(a_			).numpy().tolist()			):
  										lowerCAmelCase_     :							Tuple             =    token_type_ids_example[:, 0].tolist()[i]
  										lowerCAmelCase_     :							Union[str, Any]             =    token_type_ids_example[:, 1].tolist()[i] - 1
  										lowerCAmelCase_     :							Tuple             =    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_			)
  
  								lowerCAmelCase_     :							Optional[Any]             =    {key: np.array(coords_to_probs[key]			).mean() > 0.5 for key in coords_to_probs}
  
  						lowerCAmelCase_     :							str             =    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_							:			Tuple		,    **a_							:			List[Any]			):
  				lowerCAmelCase_     :							int             =    self._args_parser(*a_		,    **a_			)
  
  				lowerCAmelCase_     :							str             =    super().__call__(a_		,    **a_			)
  				if len(a_			) == 1:
  						return results[0]
  				return results
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Tuple		,    a_							:			int=None		,    a_							:			Union[str, Any]=None		,    a_							:			str=None		,    **a_							:			Tuple			):
  				lowerCAmelCase_     :							str             =    {}
  				if padding is not None:
  						lowerCAmelCase_     :							str             =    padding
  				if truncation is not None:
  						lowerCAmelCase_     :							str             =    truncation
  
  				lowerCAmelCase_     :							Any             =    {}
  				if sequential is not None:
  						lowerCAmelCase_     :							str             =    sequential
  				return preprocess_params, forward_params, {}
  
  
  
  
  
  		def      lowerCamelCase (     self							:			List[Any]		,    a_							:			Optional[int]		,    a_							:			List[str]=None		,    a_							:			List[Any]=True		,    a_							:			Optional[Any]=None			):
  				if truncation is None:
  						if self.type == "tapas":
  								lowerCAmelCase_     :							Union[str, Any]             =    "drop_rows_to_fit"
  						else:
  								lowerCAmelCase_     :							List[str]             =    "do_not_truncate"
  
  				lowerCAmelCase_       ,			lowerCAmelCase_     :							Tuple             =    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_     :							Dict             =    self.tokenizer(a_		,    a_		,    return_tensors=self.framework		,    truncation=a_		,    padding=a_			)
  				lowerCAmelCase_     :							Optional[int]             =    table
  				return inputs
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Any		,    a_							:			Optional[Any]		,    a_							:			List[str]=False			):
  				lowerCAmelCase_     :							Optional[Any]             =    model_inputs.pop("table"			)
  
  				if self.type == "tapas":
  						if sequential:
  								lowerCAmelCase_     :							Dict             =    self.sequential_inference(**a_			)
  						else:
  								lowerCAmelCase_     :							List[Any]             =    self.batch_inference(**a_			)
  				else:
  						lowerCAmelCase_     :							Optional[int]             =    self.model.generate(**a_			)
  				lowerCAmelCase_     :							Any             =    {"model_inputs": model_inputs, "table": table, "outputs": outputs}
  				return model_outputs
  
  
  
  
  
  		def      lowerCamelCase (     self							:			Any		,    a_							:			str			):
  				lowerCAmelCase_     :							List[str]             =    model_outputs["model_inputs"]
  				lowerCAmelCase_     :							str             =    model_outputs["table"]
  				lowerCAmelCase_     :							str             =    model_outputs["outputs"]
  				if self.type == "tapas":
  						if self.aggregate:
  								lowerCAmelCase_       ,			lowerCAmelCase_     :							Any             =    outputs[:2]
  								lowerCAmelCase_     :							Any             =    self.tokenizer.convert_logits_to_predictions(a_		,    a_		,    a_			)
  								lowerCAmelCase_       ,			lowerCAmelCase_     :							Any             =    predictions
  								lowerCAmelCase_     :							Union[str, Any]             =    {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(a_			)}
  
  								lowerCAmelCase_     :							int             =    self.model.config.no_aggregation_label_index
  								lowerCAmelCase_     :							List[Any]             =    {
  								    i: aggregators[i] + " > " for i, pred in enumerate(a_			) if pred != no_agg_label_index
  								}
  						else:
  								lowerCAmelCase_     :							Optional[Any]             =    outputs[0]
  								lowerCAmelCase_     :							List[Any]             =    self.tokenizer.convert_logits_to_predictions(a_		,    a_			)
  								lowerCAmelCase_     :							List[Any]             =    predictions[0]
  								lowerCAmelCase_     :							Optional[int]             =    {}
  								lowerCAmelCase_     :							Union[str, Any]             =    {}
  						lowerCAmelCase_     :							Union[str, Any]             =    []
  						for index, coordinates in enumerate(a_			):
  								lowerCAmelCase_     :							Any             =    [table.iat[coordinate] for coordinate in coordinates]
  								lowerCAmelCase_     :							Tuple             =    aggregators.get(a_		,    ""			)
  								lowerCAmelCase_     :							List[str]             =    aggregators_prefix.get(a_		,    ""			)
  								lowerCAmelCase_     :							List[str]             =    {
  								    "answer": aggregator_prefix + ", ".join(a_			),
  								    "coordinates": coordinates,
  								    "cells": [table.iat[coordinate] for coordinate in coordinates],
  								}
  								if aggregator:
  										lowerCAmelCase_     :							int             =    aggregator
  
  								answers.append(a_			)
  						if len(a_			) == 0:
  								raise PipelineException("Empty answer"			)
  				else:
  						lowerCAmelCase_     :							int             =    [{"answer": answer} for answer in self.tokenizer.batch_decode(a_		,    skip_special_tokens=a_			)]
  
  				return answers if len(a_			) > 1 else answers[0]
  