

'''simple docstring'''







import itertools
from dataclasses import dataclass
from typing import Any, Callable, Dict, List, Optional, Union

import pandas as pd
import pyarrow as pa

import datasets
import datasets.config
from datasets.features.features import require_storage_cast
from datasets.table import table_cast
from datasets.utils.py_utils import Literal


__lowerCamelCase						    =      datasets.utils.logging.get_logger(__name__)

__lowerCamelCase						    =      ['''names''', '''prefix''']
__lowerCamelCase						    =      ['''warn_bad_lines''', '''error_bad_lines''', '''mangle_dupe_cols''']
__lowerCamelCase						    =      ['''encoding_errors''', '''on_bad_lines''']
__lowerCamelCase						    =      ['''date_format''']


@dataclass
class    A__ ( datasets.BuilderConfig     ):
    lowercase		   =						","
    lowercase		   =						None
    lowercase		   =						"infer"
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						True
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						False
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						True
    lowercase		   =						True
    lowercase		   =						False
    lowercase		   =						True
    lowercase		   =						None
    lowercase		   =						"."
    lowercase		   =						None
    lowercase		   =						'"'
    lowercase		   =						0
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						None
    lowercase		   =						True
    lowercase		   =						True
    lowercase		   =						0
    lowercase		   =						True
    lowercase		   =						False
    lowercase		   =						None
    lowercase		   =						10_000
    lowercase		   =						None
    lowercase		   =						"strict"
    lowercase		   =						"error"
    lowercase		   =						None



    def    snake_case_     (   self    )  -> List[str]:





           '''simple docstring'''
           if self.delimiter is not None:
                  A_		   = self.delimiter
           if self.column_names is not None:
                  A_		   = self.column_names







    @property
    def    snake_case_     (   self    )  -> Tuple:





           '''simple docstring'''
           A_		   = {
               """sep""": self.sep,
               """header""": self.header,
               """names""": self.names,
               """index_col""": self.index_col,
               """usecols""": self.usecols,
               """prefix""": self.prefix,
               """mangle_dupe_cols""": self.mangle_dupe_cols,
               """engine""": self.engine,
               """converters""": self.converters,
               """true_values""": self.true_values,
               """false_values""": self.false_values,
               """skipinitialspace""": self.skipinitialspace,
               """skiprows""": self.skiprows,
               """nrows""": self.nrows,
               """na_values""": self.na_values,
               """keep_default_na""": self.keep_default_na,
               """na_filter""": self.na_filter,
               """verbose""": self.verbose,
               """skip_blank_lines""": self.skip_blank_lines,
               """thousands""": self.thousands,
               """decimal""": self.decimal,
               """lineterminator""": self.lineterminator,
               """quotechar""": self.quotechar,
               """quoting""": self.quoting,
               """escapechar""": self.escapechar,
               """comment""": self.comment,
               """encoding""": self.encoding,
               """dialect""": self.dialect,
               """error_bad_lines""": self.error_bad_lines,
               """warn_bad_lines""": self.warn_bad_lines,
               """skipfooter""": self.skipfooter,
               """doublequote""": self.doublequote,
               """memory_map""": self.memory_map,
               """float_precision""": self.float_precision,
               """chunksize""": self.chunksize,
               """encoding_errors""": self.encoding_errors,
               """on_bad_lines""": self.on_bad_lines,
               """date_format""": self.date_format,
           }

           # some kwargs must not be passed if they don't have a default value
           # some others are deprecated and we can also not pass them if they are the default value
           for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS:
                  if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig()						,			UpperCamelCase__    ):
                         del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 2.0 new arguments
           if not (datasets.config.PANDAS_VERSION.major >= 2):
                  for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS:
                         del pd_read_csv_kwargs[pd_read_csv_parameter]

        # Remove 1.3 new arguments
           if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3):
                  for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS:
                         del pd_read_csv_kwargs[pd_read_csv_parameter]

           return pd_read_csv_kwargs


class    A__ ( datasets.ArrowBasedBuilder     ):
    lowercase		   =						CsvConfig



    def    snake_case_     (   self    )  -> Dict:





           '''simple docstring'''
           return datasets.DatasetInfo(features=self.config.features    )



    def    snake_case_     (   self						,			UpperCamelCase__    )  -> List[str]:





           '''simple docstring'''
           if not self.config.data_files:
                  raise ValueError(f'''At least one data file must be specified, but got data_files={self.config.data_files}'''    )
           A_		   = dl_manager.download_and_extract(self.config.data_files    )
           if isinstance(UpperCamelCase__						,			(str, list, tuple)    ):
                  A_		   = data_files
                  if isinstance(UpperCamelCase__						,			UpperCamelCase__    ):
                         A_		   = [files]
                  A_		   = [dl_manager.iter_files(UpperCamelCase__    ) for file in files]
                  return [datasets.SplitGenerator(name=datasets.Split.TRAIN						,			gen_kwargs={"""files""": files}    )]
           A_		   = []
           for split_name, files in data_files.items():
                  if isinstance(UpperCamelCase__						,			UpperCamelCase__    ):
                         A_		   = [files]
                  A_		   = [dl_manager.iter_files(UpperCamelCase__    ) for file in files]
                  splits.append(datasets.SplitGenerator(name=UpperCamelCase__						,			gen_kwargs={"""files""": files}    )    )
           return splits



    def    snake_case_     (   self						,			UpperCamelCase__    )  -> pa.Table:





           '''simple docstring'''
           if self.config.features is not None:
                  A_		   = self.config.features.arrow_schema
                  if all(not require_storage_cast(UpperCamelCase__    ) for feature in self.config.features.values()    ):
                         # cheaper cast
                         A_		   = pa.Table.from_arrays([pa_table[field.name] for field in schema]						,			schema=UpperCamelCase__    )
                  else:
                         # more expensive cast; allows str <-> int/float or str to Audio for example
                         A_		   = table_cast(UpperCamelCase__						,			UpperCamelCase__    )
           return pa_table







    def    snake_case_     (   self						,			UpperCamelCase__    )  -> Tuple:





           '''simple docstring'''
           A_		   = self.config.features.arrow_schema if self.config.features else None
           # dtype allows reading an int column as str
           A_		   = (
               {
                   name: dtype.to_pandas_dtype() if not require_storage_cast(UpperCamelCase__    ) else object
                   for name, dtype, feature in zip(schema.names						,			schema.types						,			self.config.features.values()    )
               }
               if schema is not None
               else None
           )
           for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCamelCase__    )    ):
                  A_		   = pd.read_csv(UpperCamelCase__						,			iterator=UpperCamelCase__						,			dtype=UpperCamelCase__						,			**self.config.pd_read_csv_kwargs    )
                  try:
                         for batch_idx, df in enumerate(UpperCamelCase__    ):
                                A_		   = pa.Table.from_pandas(UpperCamelCase__    )
                                # Uncomment for debugging (will print the Arrow table size and elements)
                                # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
                                # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
                                yield (file_idx, batch_idx), self._cast_table(UpperCamelCase__    )
                  except ValueError as e:
                         logger.error(f'''Failed to read file \'{file}\' with error {type(UpperCamelCase__    )}: {e}'''    )
                         raise



'''simple docstring'''







import json
import logging
import os
import socket

import git
import numpy as np
import torch


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d -  %(message)s''',
    datefmt='''%m/%d/%Y %H:%M:%S''',
    level=logging.INFO,
)
__lowerCamelCase						    =      logging.getLogger(__name__)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     int:
       A_		   = git.Repo(search_parent_directories=UpperCAmelCase__			)
       A_		   = {
           """repo_id""": str(UpperCAmelCase__			),
           """repo_sha""": str(repo.head.object.hexsha			),
           """repo_branch""": str(repo.active_branch			),
       }

       with open(os.path.join(UpperCAmelCase__,    """git_log.json"""			),    """w"""			) as f:
              json.dump(UpperCAmelCase__,    UpperCAmelCase__,    indent=4			)
def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Dict:
       if params.n_gpu <= 0:
              A_		   = 0
              A_		   = -1
              A_		   = True
              A_		   = False
              return

       assert torch.cuda.is_available()

       logger.info("""Initializing GPUs"""			)
       if params.n_gpu > 1:
              assert params.local_rank != -1

              A_		   = int(os.environ["""WORLD_SIZE"""]			)
              A_		   = int(os.environ["""N_GPU_NODE"""]			)
              A_		   = int(os.environ["""RANK"""]			)

              # number of nodes / node ID
              A_		   = params.world_size // params.n_gpu_per_node
              A_		   = params.global_rank // params.n_gpu_per_node
              A_		   = True

              assert params.n_nodes == int(os.environ["""N_NODES"""]			)
              assert params.node_id == int(os.environ["""NODE_RANK"""]			)

       # local job (single GPU)
       else:
              assert params.local_rank == -1

              A_		   = 1
              A_		   = 0
              A_		   = 0
              A_		   = 0
              A_		   = 1
              A_		   = 1
              A_		   = False

       # sanity checks
       assert params.n_nodes >= 1
       assert 0 <= params.node_id < params.n_nodes
       assert 0 <= params.local_rank <= params.global_rank < params.world_size
       assert params.world_size == params.n_nodes * params.n_gpu_per_node

       # define whether this is the master process / if we are in multi-node distributed mode
       A_		   = params.node_id == 0 and params.local_rank == 0
       A_		   = params.n_nodes > 1

       # summary
       A_		   = F'''--- Global rank: {params.global_rank} - '''
       logger.info(PREFIX + """Number of nodes: %i""" % params.n_nodes			)
       logger.info(PREFIX + """Node ID        : %i""" % params.node_id			)
       logger.info(PREFIX + """Local rank     : %i""" % params.local_rank			)
       logger.info(PREFIX + """World size     : %i""" % params.world_size			)
       logger.info(PREFIX + """GPUs per node  : %i""" % params.n_gpu_per_node			)
       logger.info(PREFIX + """Master         : %s""" % str(params.is_master			)			)
       logger.info(PREFIX + """Multi-node     : %s""" % str(params.multi_node			)			)
       logger.info(PREFIX + """Multi-GPU      : %s""" % str(params.multi_gpu			)			)
       logger.info(PREFIX + """Hostname       : %s""" % socket.gethostname()			)

       # set GPU device
       torch.cuda.set_device(params.local_rank			)

       # initialize multi-GPU
       if params.multi_gpu:
              logger.info("""Initializing PyTorch distributed"""			)
              torch.distributed.init_process_group(
                  init_method="""env://""",    backend="""nccl""",    )







def  UpperCAmelCase__      ( UpperCAmelCase__			)     ->     Tuple:
       np.random.seed(args.seed			)
       torch.manual_seed(args.seed			)
       if args.n_gpu > 0:
              torch.cuda.manual_seed_all(args.seed			)
