




import os
from argparse import ArgumentParser
from pathlib import Path
from shutil import copyfile, rmtree
from typing import Generator

import datasets.config
from datasets.builder import DatasetBuilder
from datasets.commands import BaseDatasetsCLICommand
from datasets.download.download_manager import DownloadMode
from datasets.load import dataset_module_factory, import_main_class
from datasets.utils.filelock import logger as fl_logger
from datasets.utils.info_utils import VerificationMode
from datasets.utils.logging import ERROR, get_logger


_lowerCAmelCase  :				Tuple						=				get_logger(__name__)



def   lowerCAmelCase						(						_lowerCAmelCase							:				List[str]		):




 """simple docstring"""







 return TestCommand(
     args.dataset  ,							args.name  ,							args.cache_dir  ,							args.data_dir  ,							args.all_configs  ,							args.save_info or args.save_infos  ,							args.ignore_verifications  ,							args.force_redownload  ,							args.clear_cache  ,							)


class      _UpperCamelCase (			lowerCAmelCase						):
      UpperCAmelCase_            =						False  # to tell pytest it's not a test class
      @staticmethod
      def 		UpperCAmelCase_  (     lowerCamelCase				:ArgumentParser )       ->     Optional[int]:
       UpperCAmelCase__								=  parser.add_parser("test"	, help="Test dataset implementation." )
       test_parser.add_argument("--name"	, type=lowerCamelCase	, default=lowerCamelCase	, help="Dataset processing name" )
       test_parser.add_argument(
           "--cache_dir"	, type=lowerCamelCase	, default=lowerCamelCase	, help="Cache directory where the datasets are stored."	, )
       test_parser.add_argument(
           "--data_dir"	, type=lowerCamelCase	, default=lowerCamelCase	, help="Can be used to specify a manual directory to get the files from."	, )
       test_parser.add_argument("--all_configs"	, action="store_true"	, help="Test all dataset configurations" )
       test_parser.add_argument(
           "--save_info"	, action="store_true"	, help="Save the dataset infos in the dataset card (README.md)" )
       test_parser.add_argument(
           "--ignore_verifications"	, action="store_true"	, help="Run the test without checksums and splits checks."	, )
       test_parser.add_argument("--force_redownload"	, action="store_true"	, help="Force dataset redownload" )
       test_parser.add_argument(
           "--clear_cache"	, action="store_true"	, help="Remove downloaded files and cached datasets after each config test"	, )
       # aliases
       test_parser.add_argument("--save_infos"	, action="store_true"	, help="alias to save_info" )
       test_parser.add_argument("dataset"	, type=lowerCamelCase	, help="Name of the dataset to download" )
       test_parser.set_defaults(func=_test_command_factory )
      def __init__(     self				:Dict	, lowerCamelCase				:str	, lowerCamelCase				:str	, lowerCamelCase				:str	, lowerCamelCase				:str	, lowerCamelCase				:bool	, lowerCamelCase				:bool	, lowerCamelCase				:bool	, lowerCamelCase				:bool	, lowerCamelCase				:bool	, )       ->     Any:
       UpperCAmelCase__								=  dataset
       UpperCAmelCase__								=  name
       UpperCAmelCase__								=  cache_dir
       UpperCAmelCase__								=  data_dir
       UpperCAmelCase__								=  all_configs
       UpperCAmelCase__								=  save_infos
       UpperCAmelCase__								=  ignore_verifications
       UpperCAmelCase__								=  force_redownload
       UpperCAmelCase__								=  clear_cache
       if clear_cache and not cache_dir:
        print(
            "When --clear_cache is used, specifying a cache directory is mandatory.\n"
            "The 'download' folder of the cache directory and the dataset builder cache will be deleted after each configuration test.\n"
            "Please provide a --cache_dir that will be used to test the dataset script." )
        exit(1 )
       if save_infos:
        UpperCAmelCase__								=  True







      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     Optional[int]:
       fl_logger().setLevel(lowerCamelCase )
       if self._name is not None and self._all_configs:
        print("Both parameters `config` and `all_configs` can't be used at once." )
        exit(1 )
       UpperCAmelCase__	,	UpperCAmelCase__								=  self._dataset, self._name
       UpperCAmelCase__								=  dataset_module_factory(lowerCamelCase )
       UpperCAmelCase__								=  import_main_class(module.module_path )
       UpperCAmelCase__								=  len(builder_cls.BUILDER_CONFIGS ) if self._all_configs and builder_cls.BUILDER_CONFIGS else 1

       def get_builders() -> Generator[DatasetBuilder, None, None]:
        if self._all_configs and builder_cls.BUILDER_CONFIGS:
         for i, config in enumerate(builder_cls.BUILDER_CONFIGS ):
          if "config_name" in module.builder_kwargs:
           yield builder_cls(
               cache_dir=self._cache_dir	, data_dir=self._data_dir	, **module.builder_kwargs	, )
          else:
           yield builder_cls(
               config_name=config.name	, cache_dir=self._cache_dir	, data_dir=self._data_dir	, **module.builder_kwargs	, )
        else:
         if "config_name" in module.builder_kwargs:
          yield builder_cls(cache_dir=self._cache_dir	, data_dir=self._data_dir	, **module.builder_kwargs )
         else:
          yield builder_cls(
              config_name=lowerCamelCase	, cache_dir=self._cache_dir	, data_dir=self._data_dir	, **module.builder_kwargs	, )

       for j, builder in enumerate(get_builders() ):
        print(f'''Testing builder \'{builder.config.name}\' ({j + 1}/{n_builders})''' )
        UpperCAmelCase__								=  os.path.exists(
            os.path.join(builder.get_imported_module_dir()	, datasets.config.DATASETDICT_INFOS_FILENAME ) )  # record checksums only if we need to update a (deprecated) dataset_infos.json
        builder.download_and_prepare(
            download_mode=DownloadMode.REUSE_CACHE_IF_EXISTS
            if not self._force_redownload
            else DownloadMode.FORCE_REDOWNLOAD	, verification_mode=VerificationMode.NO_CHECKS
            if self._ignore_verifications
            else VerificationMode.ALL_CHECKS	, try_from_hf_gcs=lowerCamelCase	, )
        builder.as_dataset()
        if self._save_infos:
         builder._save_infos()

        # If save_infos=True, the dataset card (README.md) is created next to the loaded module file.
        # The dataset_infos are saved in the YAML part of the README.md

        # Let's move it to the original directory of the dataset script, to allow the user to
        # upload them on S3 at the same time afterwards.
        if self._save_infos:
         UpperCAmelCase__								=  os.path.join(builder_cls.get_imported_module_dir()	, "README.md" )
         UpperCAmelCase__								=  Path(lowerCamelCase ).name + ".py"
         UpperCAmelCase__								=  os.path.join(lowerCamelCase	, lowerCamelCase )
         if os.path.isfile(lowerCamelCase ):
          UpperCAmelCase__								=  os.path.dirname(lowerCamelCase )
         elif os.path.isfile(lowerCamelCase ):
          UpperCAmelCase__								=  path
         elif os.path.isdir(lowerCamelCase ):  # for local directories containing only data files
          UpperCAmelCase__								=  path
         else:  # in case of a remote dataset
          UpperCAmelCase__								=  None
          print(f'''Dataset card saved at {dataset_readme_path}''' )

         # Move dataset_info back to the user
         if dataset_dir is not None:
          UpperCAmelCase__								=  os.path.join(lowerCamelCase	, "README.md" )
          copyfile(lowerCamelCase	, lowerCamelCase )
          print(f'''Dataset card saved at {user_dataset_readme_path}''' )

            # If clear_cache=True, the download folder and the dataset builder cache directory are deleted
        if self._clear_cache:
         if os.path.isdir(builder._cache_dir ):
          logger.warning(f'''Clearing cache at {builder._cache_dir}''' )
          rmtree(builder._cache_dir )
         UpperCAmelCase__								=  os.path.join(self._cache_dir	, datasets.config.DOWNLOADED_DATASETS_DIR )
         if os.path.isdir(lowerCamelCase ):
          logger.warning(f'''Clearing cache at {download_dir}''' )
          rmtree(lowerCamelCase )

       print("Test successful." )











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

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

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

       return tqa_pipeline_inputs



@add_end_docstrings(lowerCAmelCase						)
class      _UpperCamelCase (			lowerCAmelCase						):
      UpperCAmelCase_            =						"""table,query"""
      def __init__(     self				:int	, lowerCamelCase				:Any=TableQuestionAnsweringArgumentHandler()	, *lowerCamelCase				:Optional[int]	, **lowerCamelCase				:str )       ->     int:
       super().__init__(*lowerCamelCase	, **lowerCamelCase )
       UpperCAmelCase__								=  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() ) )

       UpperCAmelCase__								=  bool(getattr(self.model.config	, "aggregation_labels"	, lowerCamelCase ) ) and bool(
           getattr(self.model.config	, "num_aggregation_labels"	, lowerCamelCase ) )
       UpperCAmelCase__								=  "tapas" if hasattr(self.model.config	, "aggregation_labels" ) else None
      def 		UpperCAmelCase_  (     self				:int	, **lowerCamelCase				:Dict )       ->     Optional[int]:
       return self.model(**lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Dict	, **lowerCamelCase				:Optional[int] )       ->     Dict:
       if self.framework == "pt":
        UpperCAmelCase__								=  []
        UpperCAmelCase__								=  []
        UpperCAmelCase__								=  None
        UpperCAmelCase__								=  inputs["input_ids"].shape[0]

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

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

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

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

          UpperCAmelCase__								=  torch.from_numpy(lowerCamelCase ).type(torch.long ).to(self.device )

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

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

         all_logits.append(lowerCamelCase )

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

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

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

        UpperCAmelCase__								=  torch.cat(tuple(lowerCamelCase )	, 0 )

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

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

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

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

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

          UpperCAmelCase__								=  model_labels

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

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

         all_logits.append(lowerCamelCase )

         UpperCAmelCase__								=  tfp.distributions.Bernoulli(logits=lowerCamelCase )
         UpperCAmelCase__								=  dist_per_token.probs_parameter() * tf.cast(lowerCamelCase	, tf.floataa )

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

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

        UpperCAmelCase__								=  tf.concat(tuple(lowerCamelCase )	, 0 )

        return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(lowerCamelCase )	, 0 ))
      def __call__(     self				:str	, *lowerCamelCase				:List[Any]	, **lowerCamelCase				:List[Any] )       ->     Dict:
       UpperCAmelCase__								=  self._args_parser(*lowerCamelCase	, **lowerCamelCase )

       UpperCAmelCase__								=  super().__call__(lowerCamelCase	, **lowerCamelCase )
       if len(lowerCamelCase ) == 1:
        return results[0]
       return results
      def 		UpperCAmelCase_  (     self				:List[str]	, lowerCamelCase				:int=None	, lowerCamelCase				:Optional[int]=None	, lowerCamelCase				:int=None	, **lowerCamelCase				:Tuple )       ->     Tuple:
       UpperCAmelCase__								=  {}
       if padding is not None:
        UpperCAmelCase__								=  padding
       if truncation is not None:
        UpperCAmelCase__								=  truncation

       UpperCAmelCase__								=  {}
       if sequential is not None:
        UpperCAmelCase__								=  sequential
       return preprocess_params, forward_params, {}
      def 		UpperCAmelCase_  (     self				:Optional[int]	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Tuple=None	, lowerCamelCase				:Union[str, Any]=True	, lowerCamelCase				:str=None )       ->     Union[str, Any]:
       if truncation is None:
        if self.type == "tapas":
         UpperCAmelCase__								=  "drop_rows_to_fit"
        else:
         UpperCAmelCase__								=  "do_not_truncate"

       UpperCAmelCase__	,	UpperCAmelCase__								=  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" )
       UpperCAmelCase__								=  self.tokenizer(lowerCamelCase	, lowerCamelCase	, return_tensors=self.framework	, truncation=lowerCamelCase	, padding=lowerCamelCase )
       UpperCAmelCase__								=  table
       return inputs
      def 		UpperCAmelCase_  (     self				:Union[str, Any]	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:Optional[Any]=False )       ->     int:
       UpperCAmelCase__								=  model_inputs.pop("table" )

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







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

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

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

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





