




'''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_	(       UpperCamelCase_							):







  '''simple docstring'''

  def __call__( self				:							str					,  SCREAMING_SNAKE_CASE_				:							Dict=None					,  SCREAMING_SNAKE_CASE_				:							str=None					,  **SCREAMING_SNAKE_CASE_				:							List[Any]	)			->		str:







       '''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(__a					,  __a	) and table.get('''query'''	) is not None and table.get('''table'''	) is not None:
                 A:		Dict          =		[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:
                      A:		Optional[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(__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:
            A:		List[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.'''	)

                 A:		Dict          =		pd.DataFrame(tqa_pipeline_input['''table''']	)

       return tqa_pipeline_inputs






@add_end_docstrings(UpperCamelCase_							)
class 						lowerCAmelCase_	(       UpperCamelCase_							):







  '''simple docstring'''

  UpperCamelCase_			:      Optional[Any]										=				"""table,query"""



  def __init__( self				:							Tuple					,  SCREAMING_SNAKE_CASE_				:							str=TableQuestionAnsweringArgumentHandler()					,  *SCREAMING_SNAKE_CASE_				:							List[Any]					,  **SCREAMING_SNAKE_CASE_				:							Any	)			->		int:







       '''simple docstring'''



       super().__init__(*__a					,  **__a	)
       A:		List[Any]          =		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()	)	)

       A:		List[Any]          =		bool(getattr(self.model.config					,  '''aggregation_labels'''					,  __a	)	) and bool(
           getattr(self.model.config					,  '''num_aggregation_labels'''					,  __a	)	)
       A:		Dict          =		'tapas' if hasattr(self.model.config					,  '''aggregation_labels'''	) else None



  def 					_snake_case     ( self				:							Optional[Any]					,  **SCREAMING_SNAKE_CASE_				:							List[Any]	)			->		Dict:







       '''simple docstring'''



       return self.model(**__a	)



  def 					_snake_case     ( self				:							Union[str, Any]					,  **SCREAMING_SNAKE_CASE_				:							Optional[Any]	)			->		str:







       '''simple docstring'''



       if self.framework == "pt":
            A:		List[Any]          =		[]
            A:		List[Any]          =		[]
            A:		List[Any]          =		None
            A:		Any          =		inputs['input_ids'].shape[0]

            A:		List[Any]          =		inputs['input_ids'].to(self.device	)
            A:		Optional[Any]          =		inputs['attention_mask'].to(self.device	)
            A:		Dict          =		inputs['token_type_ids'].to(self.device	)
            A:		str          =		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:
                      A:		Dict          =		token_type_ids_example[:, 3]  # shape (seq_len,)
                      A:		List[Any]          =		np.zeros_like(prev_labels_example.cpu().numpy()	)  # shape (seq_len,)

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

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

                      A:		Any          =		torch.from_numpy(__a	).type(torch.long	).to(self.device	)

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

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

                 all_logits.append(__a	)

                 A:		int          =		torch.distributions.Bernoulli(logits=__a	)
                 A:		str          =		dist_per_token.probs * attention_mask_example.type(torch.floataa	).to(
                     dist_per_token.probs.device	)

                 A:		str          =		collections.defaultdict(__a	)
                 for i, p in enumerate(probabilities.squeeze().tolist()	):
                      A:		List[Any]          =		token_type_ids_example[:, 0].tolist()[i]
                      A:		int          =		token_type_ids_example[:, 1].tolist()[i] - 1
                      A:		Optional[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(__a	)

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

            A:		Dict          =		torch.cat(tuple(__a	)					,  0	)

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

            A:		List[Any]          =		inputs['input_ids']
            A:		Optional[int]          =		inputs['attention_mask']
            A:		Union[str, Any]          =		inputs['token_type_ids'].numpy()
            A:		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:
                      A:		Tuple          =		token_type_ids_example[:, 3]  # shape (seq_len,)
                      A:		str          =		np.zeros_like(__a					,  dtype=np.intaa	)  # shape (seq_len,)

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

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

                      A:		Any          =		model_labels

                 A:		Union[str, Any]          =		input_ids[index]
                 A:		Any          =		attention_mask[index]  # shape (seq_len,)
                 A:		Dict          =		token_type_ids[index]  # shape (seq_len, 7)
                 A:		Dict          =		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	)					,  )
                 A:		Union[str, Any]          =		outputs.logits

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

                 all_logits.append(__a	)

                 A:		int          =		tfp.distributions.Bernoulli(logits=__a	)
                 A:		List[Any]          =		dist_per_token.probs_parameter() * tf.cast(__a					,  tf.floataa	)

                 A:		int          =		collections.defaultdict(__a	)
                 A:		Optional[Any]          =		token_type_ids_example
                 for i, p in enumerate(tf.squeeze(__a	).numpy().tolist()	):
                      A:		Optional[int]          =		token_type_ids_example[:, 0].tolist()[i]
                      A:		str          =		token_type_ids_example[:, 1].tolist()[i] - 1
                      A:		Dict          =		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	)

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

            A:		int          =		tf.concat(tuple(__a	)					,  0	)

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



  def __call__( self				:							Dict					,  *SCREAMING_SNAKE_CASE_				:							Optional[Any]					,  **SCREAMING_SNAKE_CASE_				:							Optional[Any]	)			->		List[Any]:







       '''simple docstring'''



       A:		Any          =		self._args_parser(*__a					,  **__a	)

       A:		str          =		super().__call__(__a					,  **__a	)
       if len(__a	) == 1:
            return results[0]
       return results



  def 					_snake_case     ( self				:							int					,  SCREAMING_SNAKE_CASE_				:							Any=None					,  SCREAMING_SNAKE_CASE_				:							Union[str, Any]=None					,  SCREAMING_SNAKE_CASE_				:							List[str]=None					,  **SCREAMING_SNAKE_CASE_				:							Optional[Any]	)			->		Any:







       '''simple docstring'''



       A:		str          =		{}
       if padding is not None:
            A:		Dict          =		padding
       if truncation is not None:
            A:		List[Any]          =		truncation

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



  def 					_snake_case     ( self				:							Optional[Any]					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=None					,  SCREAMING_SNAKE_CASE_				:							str=True					,  SCREAMING_SNAKE_CASE_				:							Optional[Any]=None	)			->		Any:







       '''simple docstring'''



       if truncation is None:
            if self.type == "tapas":
                 A:		int          =		'drop_rows_to_fit'
            else:
                 A:		Union[str, Any]          =		'do_not_truncate'

       A:		Optional[Any]          =		pipeline_input['table'], pipeline_input['query']
       if table.empty:
            raise ValueError('''table is empty'''	)
       if query is None or query == "":
            raise ValueError('''query is empty'''	)
       A:		Optional[Any]          =		self.tokenizer(__a					,  __a					,  return_tensors=self.framework					,  truncation=__a					,  padding=__a	)
       A:		str          =		table
       return inputs



  def 					_snake_case     ( self				:							List[str]					,  SCREAMING_SNAKE_CASE_				:							Dict					,  SCREAMING_SNAKE_CASE_				:							Dict=False	)			->		Union[str, Any]:







       '''simple docstring'''



       A:		List[Any]          =		model_inputs.pop('''table'''	)

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




  def 					_snake_case     ( self				:							Dict					,  SCREAMING_SNAKE_CASE_				:							int	)			->		int:







       '''simple docstring'''



       A:		Union[str, Any]          =		model_outputs['model_inputs']
       A:		Dict          =		model_outputs['table']
       A:		Tuple          =		model_outputs['outputs']
       if self.type == "tapas":
            if self.aggregate:
                 A:		Dict          =		outputs[:2]
                 A:		Tuple          =		self.tokenizer.convert_logits_to_predictions(__a					,  __a					,  __a	)
                 A:		Tuple          =		predictions
                 A:		List[str]          =		{i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(__a	)}

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

                 answers.append(__a	)
            if len(__a	) == 0:
                 raise PipelineException('''Empty answer'''	)
       else:
            A:		Dict          =		[{'answer': answer} for answer in self.tokenizer.batch_decode(__a					,  skip_special_tokens=__a	)]

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














'''simple docstring'''






from math import gcd




def 							_SCREAMING_SNAKE_CASE	(					A	:							int = 1_20_00	)     ->			int:







   """simple docstring"""
   __snake_case					:   Dict  				=			0
   for d in range(max_d + 1	):
      for n in range(d // 3 + 1	,		(d + 1) // 2	):
         if gcd(A	,		A	) == 1:
            fractions_number += 1
   return fractions_number


if __name__ == "__main__":
      print(f'''{solution() = }''')