

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


UpperCAmelCase__ :     Dict				    =    datasets.utils.logging.get_logger(__name__)

UpperCAmelCase__ :     Dict				    =    ["""names""", """prefix"""]
UpperCAmelCase__ :     Optional[int]				    =    ["""warn_bad_lines""", """error_bad_lines""", """mangle_dupe_cols"""]
UpperCAmelCase__ :     Union[str, Any]				    =    ["""encoding_errors""", """on_bad_lines"""]
UpperCAmelCase__ :     Any				    =    ["""date_format"""]







@dataclass
class        a__       (   datasets.BuilderConfig       ):







  """simple docstring"""




  UpperCAmelCase__      : str			       =","
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : Optional[Union[int, List[int], str]]			       ="infer"
  UpperCAmelCase__      : Optional[List[str]]			       =None
  UpperCAmelCase__      : Optional[List[str]]			       =None
  UpperCAmelCase__      : Optional[Union[int, str, List[int], List[str]]]			       =None
  UpperCAmelCase__      : Optional[Union[List[int], List[str]]]			       =None
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : Optional[Literal["c", "python", "pyarrow"]]			       =None
  UpperCAmelCase__      : Dict[Union[int, str], Callable[[Any], Any]]			       =None
  UpperCAmelCase__      : Optional[list]			       =None
  UpperCAmelCase__      : Optional[list]			       =None
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : Optional[Union[int, List[int]]]			       =None
  UpperCAmelCase__      : Optional[int]			       =None
  UpperCAmelCase__      : Optional[Union[str, List[str]]]			       =None
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : str			       ="."
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : str			       ='"'
  UpperCAmelCase__      : int			       =0
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : int			       =0
  UpperCAmelCase__      : bool			       =True
  UpperCAmelCase__      : bool			       =False
  UpperCAmelCase__      : Optional[str]			       =None
  UpperCAmelCase__      : int			       =1_0_0_0_0
  UpperCAmelCase__      : Optional[datasets.Features]			       =None
  UpperCAmelCase__      : Optional[str]			       ="strict"
  UpperCAmelCase__      : Literal["error", "warn", "skip"]			       ="error"
  UpperCAmelCase__      : Optional[str]			       =None


  def  _lowercase      (			self    : List[Any]		)					->List[str]:
        """simple docstring"""







        if self.delimiter is not None:
              SCREAMING_SNAKE_CASE :      str       =   self.delimiter
        if self.column_names is not None:
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   self.column_names




  @property
  def  _lowercase      (			self    : Optional[int]		)					->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      List[str]       =   {
            """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       ):







  """simple docstring"""




  UpperCAmelCase__      : List[Any]			       =CsvConfig


  def  _lowercase      (			self    : Any		)					->Union[str, Any]:
        """simple docstring"""







        return datasets.DatasetInfo(features=self.config.features		)


  def  _lowercase      (			self    : Optional[int]				,				UpperCAmelCase__    : List[Any]		)					->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}"		)
        SCREAMING_SNAKE_CASE :      Optional[Any]       =   dl_manager.download_and_extract(self.config.data_files		)
        if isinstance(UpperCAmelCase__				,				(str, list, tuple)		):
              SCREAMING_SNAKE_CASE :      str       =   data_files
              if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		):
                    SCREAMING_SNAKE_CASE :      int       =   [files]
              SCREAMING_SNAKE_CASE :      Optional[int]       =   [dl_manager.iter_files(UpperCAmelCase__		) for file in files]
              return [datasets.SplitGenerator(name=datasets.Split.TRAIN				,				gen_kwargs={"""files""": files}		)]
        SCREAMING_SNAKE_CASE :      List[str]       =   []
        for split_name, files in data_files.items():
              if isinstance(UpperCAmelCase__				,				UpperCAmelCase__		):
                    SCREAMING_SNAKE_CASE :      List[Any]       =   [files]
              SCREAMING_SNAKE_CASE :      Optional[Any]       =   [dl_manager.iter_files(UpperCAmelCase__		) for file in files]
              splits.append(datasets.SplitGenerator(name=UpperCAmelCase__				,				gen_kwargs={"""files""": files}		)		)
        return splits


  def  _lowercase      (			self    : str				,				UpperCAmelCase__    : pa.Table		)					->pa.Table:
        """simple docstring"""







        if self.config.features is not None:
              SCREAMING_SNAKE_CASE :      int       =   self.config.features.arrow_schema
              if all(not require_storage_cast(UpperCAmelCase__		) for feature in self.config.features.values()		):
                    # cheaper cast
                    SCREAMING_SNAKE_CASE :      str       =   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
                    SCREAMING_SNAKE_CASE :      Tuple       =   table_cast(UpperCAmelCase__				,				UpperCAmelCase__		)
        return pa_table




  def  _lowercase      (			self    : List[str]				,				UpperCAmelCase__    : str		)					->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE :      Union[str, Any]       =   self.config.features.arrow_schema if self.config.features else None
        # dtype allows reading an int column as str
        SCREAMING_SNAKE_CASE :      List[str]       =   (
            {
                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__		)		):
              SCREAMING_SNAKE_CASE :      Optional[int]       =   pd.read_csv(UpperCAmelCase__				,				iterator=UpperCAmelCase__				,				dtype=UpperCAmelCase__				,				**self.config.pd_read_csv_kwargs		)
              try:
                    for batch_idx, df in enumerate(UpperCAmelCase__		):
                          SCREAMING_SNAKE_CASE :      str       =   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







def 					__lowercase      (     _A			)     ->						str:
      SCREAMING_SNAKE_CASE :      Optional[Any]       =   """"""
      for ch in key:
            if ch == " " or ch not in key_no_dups and ch.isalpha():
                  key_no_dups += ch
      return key_no_dups






def 					__lowercase      (     _A			)     ->						dict[str, str]:
      SCREAMING_SNAKE_CASE :      int       =   [chr(i + 65			) for i in range(26			)]
      # Remove duplicate characters from key
      SCREAMING_SNAKE_CASE :      List[str]       =   remove_duplicates(key.upper()			)
      SCREAMING_SNAKE_CASE :      Dict       =   len(_A			)
      # First fill cipher with key characters
      SCREAMING_SNAKE_CASE :      int       =   {alphabet[i]: char for i, char in enumerate(_A			)}
      # Then map remaining characters in alphabet to
      # the alphabet from the beginning
      for i in range(len(_A			)						,    26			):
            SCREAMING_SNAKE_CASE :      List[Any]       =   alphabet[i - offset]
            # Ensure we are not mapping letters to letters previously mapped
            while char in key:
                  offset -= 1
                  SCREAMING_SNAKE_CASE :      str       =   alphabet[i - offset]
            SCREAMING_SNAKE_CASE :      List[Any]       =   char
      return cipher_alphabet






def 					__lowercase      (     _A						,    _A			)     ->						str:
      return "".join(cipher_map.get(_A						,    _A			) for ch in message.upper()			)






def 					__lowercase      (     _A						,    _A			)     ->						str:
      SCREAMING_SNAKE_CASE :      Optional[int]       =   {v: k for k, v in cipher_map.items()}
      return "".join(rev_cipher_map.get(_A						,    _A			) for ch in message.upper()			)






def 					__lowercase      (     )     ->						None:
      SCREAMING_SNAKE_CASE :      List[Any]       =   input("""Enter message to encode or decode: """			).strip()
      SCREAMING_SNAKE_CASE :      str       =   input("""Enter keyword: """			).strip()
      SCREAMING_SNAKE_CASE :      Dict       =   input("""Encipher or decipher? E/D:"""			).strip()[0].lower()
      try:
            SCREAMING_SNAKE_CASE :      int       =   {"""e""": encipher, """d""": decipher}[option]
      except KeyError:
            raise KeyError("""invalid input option"""			)
      SCREAMING_SNAKE_CASE :      Optional[int]       =   create_cipher_map(_A			)
      print(func(_A						,    _A			)			)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  main()




